@typeberry/jam 0.0.1-d15403c → 0.0.1-ea962ea

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/typeberry.mjs +1 -1
package/typeberry.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see typeberry.mjs.LICENSE.txt */
2
- import{fileURLToPath as e}from"node:url";import{createRequire as t}from"node:module";import*as r from"lmdb";import*as s from"minimist";var i={8:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.matchingBitCount=t.intLog2=t.cidrPrefixToMaskBinaryString=t.leftPadWithZeroBit=t.dottedDecimalNotationToBinaryString=t.parseBinaryStringToBigInt=t.decimalNumberToOctetString=t.numberToBinaryString=void 0,t.numberToBinaryString=e=>e.toString(2),t.decimalNumberToOctetString=e=>{let r=t.numberToBinaryString(e);if(r.length>8)throw new Error("Given decimal in binary contains digits greater than an octet");return t.leftPadWithZeroBit(r,8)},t.parseBinaryStringToBigInt=e=>BigInt(`0b${e}`),t.dottedDecimalNotationToBinaryString=e=>e.split(".").reduce((e,r)=>e.concat(t.decimalNumberToOctetString(parseInt(r))),""),t.leftPadWithZeroBit=(e,t)=>{if(e.length>t)throw new Error(`Given string is already longer than given final length after padding: ${t}`);return"0".repeat(t-e.length).concat(e)},t.cidrPrefixToMaskBinaryString=(e,t)=>{let r;if(r="IPv4"==t?32:128,e>r)throw Error(`Value is greater than ${r}`);return`${"1".repeat(e)}${"0".repeat(r-e)}`},t.intLog2=e=>{let t=0;for(;e%2n==0n;){if(2n===e){t++;break}if((e>>=1n)%2n!=0n){t=0;break}t++}if(0==t)throw new Error(`The value of log2 for ${e.toString()} is not an integer`);return t},t.matchingBitCount=(e,t)=>{let r,s;e.length>=t.length?(r=e,s=t):(r=t,s=e);let i=0;for(;i<r.length&&r.charAt(i)===s.charAt(i);i++);return i}},54:e=>{e.exports=function e(r,s){if(!r){var i=new t(s);throw Error.captureStackTrace&&Error.captureStackTrace(i,e),i}};class t extends Error{}t.prototype.name="AssertionError"},154:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Hexadecatet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e,16):parseInt(String(e),16);let[r,i]=s.Validator.isValidIPv6Hexadecatet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(16)}}t.Hexadecatet=i},212:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4=t.IPv6Mask=t.IPv4Mask=t.IPv6=t.Asn=t.IPv4=t.AbstractIPNum=void 0;const s=r(301),i=r(660),n=r(8),o=r(8),a=r(8),c=r(8),l=r(154),h=r(984),u=r(872),d=r(984);class g{getValue(){return this.value}toBinaryString(){return a.leftPadWithZeroBit(this.value.toString(2),this.bitSize)}hasNext(){return this.value<this.maximumBitSize}hasPrevious(){return this.value>0n}isEquals(e){return this.value===e.value}isLessThan(e){return this.value<e.value}isGreaterThan(e){return this.value>e.value}isLessThanOrEquals(e){return this.value<=e.value}isGreaterThanOrEquals(e){return this.value>=e.value}}t.AbstractIPNum=g;class f extends g{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="IPv4",this.octets=[],this.separator=".","string"==typeof e){let[t,r]=this.constructFromDecimalDottedString(e);this.value=t,this.octets=r}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.octets=r}}static fromNumber(e){return new f(e)}static fromDecimalDottedString(e){return new f(e)}static fromString(e){return f.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new f(o.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return f.fromNumber(this.getValue()+1n)}previousIPNumber(){return f.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return y.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[o,a]=i.Validator.isValidIPv4String(e);if(!o)throw new Error(a.filter(e=>""!==e).toString());return t=e.split(".").map(e=>s.Octet.fromString(e)),r=BigInt(`0b${n.dottedDecimalNotationToBinaryString(e)}`),[r,t]}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv4Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e="bigint"==typeof e?e:BigInt(e),this.binaryStringToDecimalOctets(s)]}binaryStringToDecimalOctets(e){return e.length<32&&(e=a.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(o.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=f;class p extends g{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)p.startWithASPrefix(e)?this.value=BigInt(parseInt(e.substring(2))):-1!=e.indexOf(".")?this.value=BigInt(this.parseFromDotNotation(e)):this.value=BigInt(parseInt(e));else{let t=BigInt(e),[r,s]=i.Validator.isValidAsnNumber(t);if(!r)throw Error(s.filter(e=>""!==e).toString());this.value=t}}static fromString(e){return new p(e)}static fromNumber(e){return new p(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${p.AS_PREFIX}${e}`}toASPlain(){return this.value.toString()}toASDot(){return this.value.valueOf()>=65536n?this.toASDotPlus():this.toASPlain()}toASDotPlus(){let e=this.value.valueOf()/65535n;return`${e}.${this.value.valueOf()%65535n-e}`}toBinaryString(){return c.numberToBinaryString(this.value)}is16Bit(){let[e]=i.Validator.isValid16BitAsnNumber(this.value);return e}is32Bit(){return!this.is16Bit()}nextIPNumber(){return new p(this.value.valueOf()+1n)}previousIPNumber(){return new p(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(p.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=p,p.AS_PREFIX="AS";class y extends g{constructor(e){if(super(),this.bitSize=128,this.maximumBitSize=i.Validator.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE,this.type="IPv6",this.hexadecatet=[],this.separator=":","string"==typeof e){let t=u.expandIPv6Number(e),[r,s]=this.constructFromHexadecimalDottedString(t);this.value=r,this.hexadecatet=s}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.hexadecatet=r}}static fromBigInt(e){return new y(e)}static fromHexadecatet(e){return new y(e)}static fromString(e){return y.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=a.leftPadWithZeroBit(e,128);return new y(o.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new f(e).toIPv4MappedIPv6()}toString(){let e=this.hexadecatet.map(e=>e.toString()).join(":");return this.hexadecatet.length<8?"::"+e:e}getHexadecatet(){return this.hexadecatet}nextIPNumber(){return y.fromBigInt(this.getValue()+1n)}previousIPNumber(){return y.fromBigInt(this.getValue()-1n)}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv6Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e,this.binaryStringToHexadecatets(s)]}constructFromHexadecimalDottedString(e){let[t,r]=i.Validator.isValidIPv6String(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=e.split(":").map(e=>l.Hexadecatet.fromString(e));return[BigInt(`0b${d.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=h.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=y;class m extends f{constructor(e){let t,r;if(super(e),this.octets=[],[t,r]=i.Validator.isValidIPv4Mask(e),!t)throw new Error(r.filter(e=>""!==e).toString());let o=e.split(".");this.octets=o.map(e=>s.Octet.fromString(e));let a=n.dottedDecimalNotationToBinaryString(e);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class b extends y{constructor(e){let t,r;super(e),this.hexadecatet=[];let s=u.expandIPv6Number(e);if([t,r]=i.Validator.isValidIPv6Mask(s),!t)throw new Error(r.filter(e=>""!==e).toString());let n=s.split(":");this.hexadecatet=n.map(e=>l.Hexadecatet.fromString(e));let o=d.hexadectetNotationToBinaryString(s);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`),this.value=BigInt(`0b${d.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new b(e)}}t.IPv6Mask=b,t.isIPv4=function(e){return 32===e.bitSize}},259:e=>{var t,r,s=(()=>{for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return t=>{for(var r=t.length,s=new Uint8Array(3*(r-("="==t[r-1])-("="==t[r-2]))/4|0),i=0,n=0;i<r;){var o=e[t.charCodeAt(i++)],a=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=o<<2|a>>4,s[n++]=a<<4|c>>2,s[n++]=c<<6|l}return s}})(),i=(t={"wasm-binary:./blake2b.wat"(e,t){t.exports=s("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=")}},function(){return r||(0,t[Object.keys(t)[0]])((r={exports:{}}).exports,r),r.exports})(),n=WebAssembly.compile(i);e.exports=async e=>(await WebAssembly.instantiate(await n,e)).exports},287:e=>{function t(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}e.exports={isBuffer:function(e){return Buffer.isBuffer(e)||e instanceof Uint8Array},isEncoding:function(e){return Buffer.isEncoding(e)},alloc:function(e,t,r){return Buffer.alloc(e,t,r)},allocUnsafe:function(e){return Buffer.allocUnsafe(e)},allocUnsafeSlow:function(e){return Buffer.allocUnsafeSlow(e)},byteLength:function(e,t){return Buffer.byteLength(e,t)},compare:function(e,t){return Buffer.compare(e,t)},concat:function(e,t){return Buffer.concat(e,t)},copy:function(e,r,s,i,n){return t(e).copy(r,s,i,n)},equals:function(e,r){return t(e).equals(r)},fill:function(e,r,s,i,n){return t(e).fill(r,s,i,n)},from:function(e,t,r){return Buffer.from(e,t,r)},includes:function(e,r,s,i){return t(e).includes(r,s,i)},indexOf:function(e,r,s,i){return t(e).indexOf(r,s,i)},lastIndexOf:function(e,r,s,i){return t(e).lastIndexOf(r,s,i)},swap16:function(e){return t(e).swap16()},swap32:function(e){return t(e).swap32()},swap64:function(e){return t(e).swap64()},toBuffer:t,toString:function(e,r,s,i){return t(e).toString(r,s,i)},write:function(e,r,s,i,n){return t(e).write(r,s,i,n)},writeDoubleLE:function(e,r,s){return t(e).writeDoubleLE(r,s)},writeFloatLE:function(e,r,s){return t(e).writeFloatLE(r,s)},writeUInt32LE:function(e,r,s){return t(e).writeUInt32LE(r,s)},writeInt32LE:function(e,r,s){return t(e).writeInt32LE(r,s)},readDoubleLE:function(e,r){return t(e).readDoubleLE(r)},readFloatLE:function(e,r){return t(e).readFloatLE(r)},readUInt32LE:function(e,r){return t(e).readUInt32LE(r)},readInt32LE:function(e,r){return t(e).readInt32LE(r)}}},301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Octet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e):e;let[r,i]=s.Validator.isValidIPv4Octet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(10)}}t.Octet=i},405:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o=null;function a(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return a().set(e,r/1),c=e.length,r}let h=null;function u(){return null!==h&&0!==h.byteLength||(h=new Int32Array(n.memory.buffer)),h}function d(e,t){return e>>>=0,a().subarray(e/1,e/1+t)}t.exports.hc=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),o=l(e,n.__wbindgen_malloc),a=c;n.ring_commitment(i,o,a);var t=u()[i/4+0],r=u()[i/4+1],s=d(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.KG=function(e,t,r,s,i){try{const g=n.__wbindgen_add_to_stack_pointer(-16),f=l(e,n.__wbindgen_malloc),p=c,y=l(r,n.__wbindgen_malloc),m=c,b=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(g,f,p,t,y,m,b,A,I,v);var o=u()[g/4+0],a=u()[g/4+1],h=d(o,a).slice();return n.__wbindgen_free(o,1*a,1),h}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.ZJ=function(e,t,r){try{const a=n.__wbindgen_add_to_stack_pointer(-16),h=l(e,n.__wbindgen_malloc),g=c,f=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(a,h,g,f,p,r);var s=u()[a/4+0],i=u()[a/4+1],o=d(s,i).slice();return n.__wbindgen_free(s,1*i,1),o}finally{n.__wbindgen_add_to_stack_pointer(16)}};const g=s(928).join(i,"bandersnatch_bg.wasm"),f=s(896).readFileSync(g),p=new WebAssembly.Module(f),y=new WebAssembly.Instance(p,{});n=y.exports},412:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4CidrRange=t.IPv6CidrRange=t.IPv4CidrRange=t.AbstractIPRange=t.RangedSet=void 0;const s=r(212),i=r(516),n=r(8),o=r(660);class a{constructor(e,t){if(this.first=e,this.last=t,e.isGreaterThan(t))throw new Error(`${e.toString()} should be lower than ${t.toString()}`);this.currentValue=e,this.bitValue=BigInt(e.bitSize)}static fromSingleIP(e){return new a(e,e)}static fromCidrRange(e){return new a(e.getFirst(),e.getLast())}static fromRangeString(e){let t=e.split("-").map(e=>e.trim());if(2!==t.length)throw new Error("Argument should be in the format firstip-lastip");let[r,i]=t,[n]=o.Validator.isValidIPv4String(r),[c]=o.Validator.isValidIPv4String(i),[l]=o.Validator.isValidIPv6String(r),[h]=o.Validator.isValidIPv6String(i);if(n&&c)return new a(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&h)return new a(s.IPv6.fromHexadecatet(r),s.IPv6.fromHexadecatet(i));throw new Error("First IP and Last IP should be valid and same type")}getFirst(){return this.first}getLast(){return this.last}getSize(){return this.last.getValue()-this.first.getValue()+1n}toRangeString(){return`${this.getFirst()}-${this.getLast()}`}inside(e){return e.contains(this)}contains(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return t.isLessThanOrEquals(s)&&r.isGreaterThanOrEquals(i)}isEquals(e){return this.getFirst().isEquals(e.getFirst())&&this.getLast().isEquals(e.getLast())}isLessThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()<e.getSize():this.getFirst().isLessThan(e.getFirst()))}isGreaterThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()>e.getSize():this.getFirst().isGreaterThan(e.getFirst()))}isOverlapping(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.isGreaterThan(s)&&r.isLessThanOrEquals(i)&&t.isLessThan(s)||i.isGreaterThan(t)&&i.isLessThanOrEquals(r)&&s.isLessThan(t)}isCidrAble(){if(1n===this.getSize())return!0;try{let e=n.intLog2(this.getSize()),t=n.parseBinaryStringToBigInt(n.cidrPrefixToMaskBinaryString(e,s.isIPv4(this.currentValue)?"IPv4":"IPv6"));return this.first.getValue()===(t&this.first.getValue())}catch(e){return!1}}toCidrRange(){return s.isIPv4(this.currentValue)?this.toIPv4CidrRange():this.toIPv6CidrRange()}isConsecutive(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.hasNext()&&r.nextIPNumber().isEquals(s)||i.hasNext()&&i.nextIPNumber().isEquals(t)}union(e){if(this.isEquals(e))return new a(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new a(this.getFirst(),e.getLast()):new a(e.getFirst(),this.getLast());if(this.contains(e))return new a(this.getFirst(),this.getLast());if(e.contains(this))return new a(e.getFirst(),e.getLast());throw new Error("Ranges do not overlap nor are equal")}prepend(e){if(e.getLast().nextIPNumber().isEquals(this.getFirst()))return new a(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new a(this.getFirst(),e.getLast());throw new Error("Range to append must be adjacent")}subtract(e){if(!this.isOverlapping(e))throw new Error("Cannot subtract ranges that are not overlapping");if(!this.isLessThan(e))throw new Error("Cannot subtract a larger range from this range");return new a(this.getFirst(),e.getLast())}takeSubRange(e,t){if(e+t>this.getSize())throw new RangeError("Requested range is greater than what can be taken");if(0n===t)throw new Error("Sub range cannot be zero");let r=this.getFirst().value+e,i=s.isIPv4(this.getFirst())?s.IPv4.fromNumber(r):s.IPv6.fromBigInt(r),n=i.value+(t-1n),o=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new a(i,o)}difference(e){if(e.getSize()>this.getSize())throw new Error("Range is greater than range to be subtracted from");if(!this.contains(e))throw new Error("Range to subtract is not contained in this range");let t=[];try{t.push(new a(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new a(e.getLast().nextIPNumber(),this.getLast()))}catch(e){}return t}*take(e){let t=this.getFirst(),r=void 0===e?this.getSize().valueOf():e;for(;r>0;)r--,yield t,t=t.nextIPNumber()}*[Symbol.iterator](){yield*this.take()}toIPv4CidrRange(){let e=new l(s.IPv4.fromNumber(this.getFirst().getValue()),i.IPv4Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}toIPv6CidrRange(){let e=new h(s.IPv6.fromBigInt(this.getFirst().getValue()),i.IPv6Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}}t.RangedSet=a;class c{hasNextRange(){let e=this.getSize();return 2n**this.bitValue-e>=this.getFirst().getValue()+e}hasPreviousRange(){return this.getSize()<=this.getFirst().getValue()}toRangeSet(){return new a(this.getFirst(),this.getLast())}inside(e){return this.toRangeSet().inside(e.toRangeSet())}contains(e){return this.toRangeSet().contains(e.toRangeSet())}toRangeString(){return this.toRangeSet().toRangeString()}isOverlapping(e){return this.toRangeSet().isOverlapping(e.toRangeSet())}isConsecutive(e){return this.toRangeSet().isConsecutive(e.toRangeSet())}isCidrMergeable(e){const t=BigInt(n.matchingBitCount(this.getFirst().toBinaryString(),e.getFirst().toBinaryString()));return this.getPrefix().value-t===1n&&this.isConsecutive(e)&&this.getSize()===e.getSize()}isMergeable(e){return this.isCidrMergeable(e)||this.contains(e)||this.inside(e)}isEquals(e){return this.toRangeSet().isEquals(e.toRangeSet())}merge(e){if(!this.isCidrMergeable(e))throw new Error(`Cannot merge. Ranges (${this.toRangeString()},${e.toRangeString()}) are not consecutive and/or of same size`);return this.newInstance(this.getFirst(),this.getPrefix().merge())}*takeStream(e){return this.toRangeSet().take(e)}*[Symbol.iterator](){yield*this.toRangeSet()}}t.AbstractIPRange=c;class l extends c{constructor(e,t){super(),this.ipv4=e,this.cidrPrefix=t,this.bitValue=32n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(a),i.IPv4Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv4.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv4.fromNumber(this.ipv4.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv4)}newInstance(e,t){return new l(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize()){let t=o.Validator.takeOutOfRangeSizeMessage.replace("$count",e.toString()).replace("$size",this.getSize().toString());throw new Error(t)}for(let s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(32n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv4Prefix.fromNumber(e+1n),r=this.getFirst(),s=new l(r,t),n=s.getLast().nextIPNumber();return[s,new l(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new l(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new l(new s.IPv4(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new l(new s.IPv4(t),this.cidrPrefix)}}}t.IPv4CidrRange=l;class h extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new h(s.IPv6.fromHexadecatet(a),i.IPv6Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv6.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv6.fromBigInt(this.ipv6.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv6)}newInstance(e,t){return new h(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize())throw new Error(`${e.toString()} is greater than ${this.getSize().toString()}, the size of the range`);for(var s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(128n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv6Prefix.fromNumber(e+1n),r=this.getFirst(),s=new h(r,t),n=s.getLast().nextIPNumber();return[s,new h(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new h(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new h(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new h(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=h;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),o=e.cidrPrefix.toMask().getValue(),a=n.leftPadWithZeroBit((o^i).toString(2),r);return d(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(a)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(a))};function d(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=d},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},516:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4Prefix=t.IPv6Prefix=t.IPv4Prefix=void 0;const s=r(660),i=r(212),n=r(8),o=r(984),a=r(154);class c{constructor(e){let t,r;if(this.type="IPv4",this.bitValue=32n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv4"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new c(e)}static fromRangeSize(e){let t=1n===e?32:32-h(e,s.Validator.IPV4_SIZE);return c.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(Number(32n-this.value));return i.IPv4Mask.fromDecimalDottedString(this.toDecimalNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new c(this.value-1n)}split(){return new c(this.value+1n)}toDecimalNotation(e){return`${n.parseBinaryStringToBigInt(e.substr(0,8))}.${n.parseBinaryStringToBigInt(e.substr(8,8))}.${n.parseBinaryStringToBigInt(e.substr(16,8))}.${n.parseBinaryStringToBigInt(e.substr(24,8))}`}}t.IPv4Prefix=c;class l{constructor(e){let t,r;if(this.type="IPv6",this.bitValue=128n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv6"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new l(e)}static fromRangeSize(e){let t=1n===e?128:128-h(e,s.Validator.IPV6_SIZE);return l.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(128-Number(this.value));return i.IPv6Mask.fromHexadecatet(this.toHexadecatetNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new l(this.value-1n)}split(){return new l(this.value+1n)}toHexadecatetNotation(e){return e.match(/.{1,16}/g).map(e=>a.Hexadecatet.fromString(o.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function h(e,t){let r=t>s.Validator.IPV4_SIZE?"IPv6":"IPv4";if(e>t||0n===e)throw new Error(s.Validator.invalidIPRangeSizeMessage.replace("$iptype",r));try{return n.intLog2(e)}catch(e){throw new Error(s.Validator.invalidIPRangeSizeForCidrMessage)}}t.IPv6Prefix=l,t.isIPv4Prefix=function(e){return"IPv4"===e.type}},578:(e,t,r)=>{var s=r(54),i=r(287),n=null,o="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),a=64,c=[];e.exports=p;var l=e.exports.BYTES_MIN=16,h=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),d=e.exports.KEYBYTES_MAX=64,g=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),f=e.exports.PERSONALBYTES=16;function p(e,t,r,i,o){if(!(this instanceof p))return new p(e,t,r,i,o);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==o&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=h,"digestLength must be at most "+h+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=u,"key must be at least "+u+", was given "+t.length),s(t.length<=d,"key must be at least "+d+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===g,"salt must be exactly "+g+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===f,"personal must be exactly "+f+", was given "+i.length))),c.length||(c.push(a),a+=216),this.digestLength=e,this.finalized=!1,this.pointer=c.pop(),this._memory=new Uint8Array(n.memory.buffer),this._memory.fill(0,0,64),this._memory[0]=this.digestLength,this._memory[1]=t?t.length:0,this._memory[2]=1,this._memory[3]=1,r&&this._memory.set(r,32),i&&this._memory.set(i,48),this.pointer+216>this._memory.length&&this._realloc(this.pointer+216),n.blake2b_init(this.pointer,this.digestLength),t&&(this.update(t),this._memory.fill(0,a,a+t.length),this._memory[this.pointer+200]=128)}function y(){}p.prototype._realloc=function(e){n.memory.grow(Math.max(0,Math.ceil(Math.abs(e-this._memory.length)/65536))),this._memory=new Uint8Array(n.memory.buffer)},p.prototype.update=function(e){return s(!1===this.finalized,"Hash instance finalized"),s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),a+e.length>this._memory.length&&this._realloc(a+e.length),this._memory.set(e,a),n.blake2b_update(this.pointer,a,a+e.length),this},p.prototype.digest=function(e){if(s(!1===this.finalized,"Hash instance finalized"),this.finalized=!0,c.push(this.pointer),n.blake2b_final(this.pointer),!e||"binary"===e)return this._memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if("string"==typeof e)return i.toString(this._memory,e,this.pointer+128,this.pointer+128+this.digestLength);s(e instanceof Uint8Array&&e.length>=this.digestLength,"input must be Uint8Array or Buffer");for(var t=0;t<this.digestLength;t++)e[t]=this._memory[this.pointer+128+t];return e},p.prototype.final=p.prototype.digest,p.WASM=n,p.SUPPORTED="undefined"!=typeof WebAssembly,p.ready=function(e){return e||(e=y),o?o.then(()=>e(),e):e(new Error("WebAssembly not supported"))},p.prototype.ready=p.ready,p.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},p.prototype.setPartialHash=function(e){this._memory.set(e,this.pointer)}},618:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||t.hasOwnProperty(r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(8),t),i(r(154),t),i(r(984),t),i(r(212),t),i(r(429),t),i(r(951),t),i(r(412),t),i(r(872),t),i(r(301),t),i(r(516),t),i(r(660),t)},625:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o={};o.__wbindgen_placeholder__=t.exports;let a=null;function c(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let l=0;function h(e,t){const r=t(1*e.length,1)>>>0;return c().set(e,r/1),l=e.length,r}t.exports.verify_ed25519=function(e){const t=h(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,o,a=(i=s[0],o=s[1],i>>>=0,c().subarray(i/1,i/1+o)).slice();return n.__wbindgen_free(s[0],1*s[1],1),a},t.exports.verify_ed25519_batch=function(e){const t=h(e,n.__wbindgen_malloc),r=l;return 0!==n.verify_ed25519_batch(t,r)},t.exports.__wbindgen_init_externref_table=function(){const e=n.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)};const u=s(928).join(i,"ed25519_wasm_bg.wasm"),d=s(896).readFileSync(u),g=new WebAssembly.Module(d),f=new WebAssembly.Instance(g,o);n=f.exports,t.exports.__wasm=n,n.__wbindgen_start()},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Validator=void 0;const s=r(8),i=r(8),n=r(872),o=r(984),a=r(984);class c{static isWithinRange(e,t,r){return e>=t&&e<=r}static isValidAsnNumber(e){let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return[t,t?[]:[c.invalidAsnRangeMessage]]}static isValid16BitAsnNumber(e){let t=c.isWithinRange(e,0n,c.SIXTEEN_BIT_SIZE);return[t,t?[]:[c.invalid16BitAsnRangeMessage]]}static isValidIPv4Number(e){e="bigint"==typeof e?e:BigInt(e);let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv4NumberMessage]]}static isValidIPv6Number(e){let t=this.isWithinRange(e,0n,this.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv6NumberMessage]]}static isValidIPv4Octet(e){let t=this.isWithinRange(e,0n,this.EIGHT_BIT_SIZE);return[t,t?[]:[c.invalidOctetRangeMessage]]}static isValidIPv6Hexadecatet(e){let t=this.isWithinRange(e,0n,this.SIXTEEN_BIT_SIZE);return t?[t,[]]:[t,[c.invalidHexadecatetMessage]]}static isValidIPv4String(e){let t=e.split(".");if(4!=t.length||t.includes(""))return[!1,[c.invalidOctetCountMessage]];let r=t.every(e=>!!c.isNumeric(e)&&c.isValidIPv4Octet(BigInt(e))[0]);return r?(r=c.IPV4_PATTERN.test(e),[r,r?[]:[c.invalidIPv4PatternMessage]]):[!1,[c.invalidOctetRangeMessage]]}static isValidIPv6String(e){try{let t=n.expandIPv6Number(e).split(":");if(8!=t.length)return[!1,[c.invalidHexadecatetCountMessage]];let r=t.every(e=>!!c.isHexadecatet(e)&&c.isValidIPv6Hexadecatet(BigInt(`0x${e}`))[0]);return r?(r=c.IPV6_PATTERN.test(e),[r,r?[]:[c.invalidIPv6PatternMessage]]):[!1,[c.invalidHexadecatetMessage]]}catch(e){return[!1,[e]]}}static isValidPrefixValue(e,t){if("IPv4"===t){let t=c.isWithinRange(BigInt(e),0n,32n);return[t,t?[]:[c.invalidPrefixValueMessage]]}if("IPv6"===t){let t=c.isWithinRange(BigInt(e),0n,128n);return[t,t?[]:[c.invalidPrefixValueMessage]]}return[!1,[c.invalidInetNumType]]}static isValidIPv4Mask(e){let t=s.dottedDecimalNotationToBinaryString(e),r=c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv6Mask(e){let t=a.hexadectetNotationToBinaryString(e),r=c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv4CidrNotation(e){let t=e.split("/");if(2!==t.length||0===t[0].length||0===t[1].length)return[!1,[c.invalidIPv4CidrNotationMessage]];let r=t[0],s=t[1];if(isNaN(Number(s)))return[!1,[c.invalidIPv4CidrNotationMessage]];let[i,n]=c.isValidIPv4String(r),[o,a]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&o,h=n.concat(a);return l?[l,[]]:[l,h]}static isValidIPv4CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv4CidrNotation,s.dottedDecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv4"))}static isValidIPv6CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv6CidrNotation,o.colonHexadecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv6"))}static isValidCidrRange(e,t,r,s){let i=t(e);if(!i[0])return i;let n=e.split("/"),o=n[0],a=n[1],l=BigInt(`0b${r(o)}`),h=(l&BigInt(`0b${s(parseInt(a))}`))===l;return h?[h,[]]:[h,[c.InvalidIPCidrRangeMessage]]}static isValidIPv4RangeString(e){return this.isValidRange(e,c.isValidIPv4String,(e,t)=>BigInt(`0b${s.dottedDecimalNotationToBinaryString(e)}`)>=BigInt(`0b${s.dottedDecimalNotationToBinaryString(t)}`))}static isValidIPv6RangeString(e){return this.isValidRange(e,c.isValidIPv6String,(e,t)=>BigInt(`0b${a.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${a.hexadectetNotationToBinaryString(t)}`))}static isValidRange(e,t,r){let s=e.split("-").map(e=>e.trim());if(2!==s.length||0===s[0].length||0===s[1].length)return[!1,[c.invalidRangeNotationMessage]];let i=s[0],n=s[1],[o,a]=t(i),[l,h]=t(n),u=o&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let d=a.concat(h);return u?[u,[]]:[u,d]}static isValidIPv6CidrNotation(e){let t=c.IPV6_RANGE_PATTERN.test(e);return t?[t,[]]:[t,[c.invalidIPv6CidrNotationString]]}static isValidBinaryString(e){return/^([10])+$/.test(e)?[!0,[]]:[!1,[c.invalidBinaryStringErrorMessage]]}static isNumeric(e){return/^(\d+)$/.test(e)}static isHexadecatet(e){return/^[0-9A-Fa-f]{4}$/.test(e)}}t.Validator=c,c.IPV4_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/),c.IPV6_PATTERN=new RegExp(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/),c.IPV4_RANGE_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/)([1-9]|[1-2][0-9]|3[0-2])$/),c.IPV6_RANGE_PATTERN=new RegExp(/^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/),c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,32}(0){0,32}$/),c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,128}(0){0,128}$/),c.EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(8)}`),c.SIXTEEN_BIT_SIZE=BigInt(`0b${"1".repeat(16)}`),c.THIRTY_TWO_BIT_SIZE=BigInt(`0b${"1".repeat(32)}`),c.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(128)}`),c.IPV4_SIZE=BigInt("4294967296"),c.IPV6_SIZE=BigInt("340282366920938463463374607431768211456"),c.invalidAsnRangeMessage="ASN number given less than zero or is greater than 32bit",c.invalid16BitAsnRangeMessage="ASN number given less than zero or is greater than 16bit",c.invalidIPv4NumberMessage="IPv4 number given less than zero or is greater than 32bit",c.invalidIPv6NumberMessage="IPv6 number given less than zero or is greater than 128bit",c.invalidOctetRangeMessage="Value given contains an invalid Octet; Value is less than zero or is greater than 8bit",c.invalidHexadecatetMessage="The value given is less than zero or is greater than 16bit",c.invalidOctetCountMessage="An IP4 number cannot have less or greater than 4 octets",c.invalidHexadecatetCountMessage="An IP6 number must have exactly 8 hexadecatet",c.invalidMaskMessage="The Mask is invalid",c.invalidPrefixValueMessage="A Prefix value cannot be less than 0 or greater than 32",c.invalidIPv4CidrNotationMessage="Cidr notation should be in the form [ip number]/[range]",c.InvalidIPCidrRangeMessage="Given IP number portion must is not the start of the range",c.invalidRangeNotationMessage="Range notation should be in the form [first ip]-[last ip]",c.invalidRangeFirstNotGreaterThanLastMessage="First IP in [first ip]-[last ip] must be less than Last IP",c.invalidIPv6CidrNotationString="A Cidr notation string should contain an IPv6 number and prefix",c.takeOutOfRangeSizeMessage="$count is greater than $size, the size of the range",c.cannotSplitSingleRangeErrorMessage="Cannot split an IP range with a single IP number",c.invalidInetNumType="Given ipNumType must be either InetNumType.IPv4 or InetNumType.IPv6",c.invalidBinaryStringErrorMessage="Binary string should contain only contiguous 1s and 0s",c.invalidIPRangeSizeMessage="Given size is zero or greater than maximum size of $iptype",c.invalidIPRangeSizeForCidrMessage="Given size can't be created via cidr prefix",c.invalidIPv4PatternMessage="Given IPv4 is not confirm to a valid IPv6 address",c.invalidIPv6PatternMessage="Given IPv6 is not confirm to a valid IPv6 address"},675:(e,t,r)=>{var s=r(54),i=r(578);function n(e,t,r){var s=e[t]+e[r],i=e[t+1]+e[r+1];s>=4294967296&&i++,e[t]=s,e[t+1]=i}function o(e,t,r,s){var i=e[t]+r;r<0&&(i+=4294967296);var n=e[t+1]+s;i>=4294967296&&n++,e[t]=i,e[t+1]=n}function a(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,a){var c=d[i],l=d[i+1],h=d[a],g=d[a+1];n(u,e,t),o(u,e,c,l);var f=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=f,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=f>>>24^p<<8,u[t+1]=p>>>24^f<<8,n(u,e,t),o(u,e,h,g),f=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=f>>>16^p<<16,u[s+1]=p>>>16^f<<16,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^f<<1,u[t+1]=f>>>31^p<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),h=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),u=new Uint32Array(32),d=new Uint32Array(32);function g(e,t){var r=0;for(r=0;r<16;r++)u[r]=e.h[r],u[r+16]=l[r];for(u[24]=u[24]^e.t,u[25]=u[25]^e.t/4294967296,t&&(u[28]=~u[28],u[29]=~u[29]),r=0;r<32;r++)d[r]=a(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,h[16*r+0],h[16*r+1]),c(2,10,18,26,h[16*r+2],h[16*r+3]),c(4,12,20,28,h[16*r+4],h[16*r+5]),c(6,14,22,30,h[16*r+6],h[16*r+7]),c(0,10,20,30,h[16*r+8],h[16*r+9]),c(2,12,22,24,h[16*r+10],h[16*r+11]),c(4,14,16,26,h[16*r+12],h[16*r+13]),c(6,8,18,28,h[16*r+14],h[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var f=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function p(e,t,r,s){f.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,f[0]=e,t&&(f[1]=t.length),f[2]=1,f[3]=1,r&&f.set(r,32),s&&f.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(f,4*i);t&&(y(this,t),this.c=128)}function y(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,g(e,!1),e.c=0),e.b[e.c++]=t[r]}function m(e){return e<16?"0"+e.toString(16):e.toString(16)}p.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),y(this,e),this},p.prototype.digest=function(e){var t=e&&"binary"!==e&&"hex"!==e?e:new Uint8Array(this.outlen);return s(t instanceof Uint8Array,'out must be "binary", "hex", Uint8Array, or Buffer'),s(t.length>=this.outlen,"out must have at least outlen bytes of space"),function(e,t){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;g(e,!0);for(var r=0;r<e.outlen;r++)t[r]=e.h[r>>2]>>8*(3&r)}(this,t),"hex"===e?function(e){for(var t="",r=0;r<e.length;r++)t+=m(e[r]);return t}(t):t},p.prototype.final=p.prototype.digest,p.ready=function(e){i.ready(function(){e()})};var b=p;e.exports=function(e,t,r,i,n){return!0!==n&&(s(e>=A,"outlen must be at least "+A+", was given "+e),s(e<=I,"outlen must be at most "+I+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=v,"key must be at least "+v+", was given "+t.length),s(t.length<=w,"key must be at most "+w+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===S,"salt must be exactly "+S+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===E,"personal must be exactly "+E+", was given "+i.length))),new b(e,t,r,i)},e.exports.ready=function(e){i.ready(function(){e()})},e.exports.WASM_SUPPORTED=i.SUPPORTED,e.exports.WASM_LOADED=!1;var A=e.exports.BYTES_MIN=16,I=e.exports.BYTES_MAX=64,v=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),w=e.exports.KEYBYTES_MAX=64,S=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),E=e.exports.PERSONALBYTES=16;i.ready(function(t){t||(e.exports.WASM_LOADED=!0,e.exports=i)})},872:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.collapseIPv6Number=t.expandIPv6Number=void 0;const s=r(8),i=r(660);let n=e=>e.includes("/")?`/${e.split("/")[1]}`:"";t.expandIPv6Number=e=>{let t=e=>e.map(e=>s.leftPadWithZeroBit(e,4)).join(":");if(/(:){3,}/.test(e))throw"given IPv6 contains consecutive : more than two";const r=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);if(e.includes("::")){let s=e.split("::"),i=s[0],n=s[1],o=i.split(":").filter(e=>""!==e),a=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(o.length+a.length)),l=t(o);""!==l&&(l+=":");let h=t(a);return""!==h&&(h=":"+h),`${l}${c}${h}${r}`}return`${t(e.split(":"))}${r}`},t.collapseIPv6Number=e=>{const t=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);let r=e.split(":").map(e=>{let t=e.replace(/^0+/,"");return""!==t?t:"0"}).join(":").replace(/((^0)?(:0){2,}|(^0)(:0){1,})/,":");return":"===r.slice(-1)?`${r}:${t}`:(r=r.replace(":0:","::"),`${r}${t}`)}},884:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmNvbnN0IHsgd29ya2VyIH0gPSBhd2FpdCB0c0ltcG9ydCgiLi93b3JrZXIudHMiLCBpbXBvcnQubWV0YS51cmwpOwp3b3JrZXIubGlzdGVuVG9QYXJlbnRQb3J0KCk7Cg=="},896:e=>{e.exports=t(import.meta.url)("fs")},909:()=>{var e;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=s(e);function s(e,t){return function(r,s){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:s}),t&&t(r,s)}}void 0!==t.Reflect&&(r=s(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,s="function"==typeof Symbol,i=s&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",n=s&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,l={create:o?function(){return Q(Object.create(null))}:a?function(){return Q({__proto__:null})}:function(){return Q({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},h=Object.getPrototypeOf(Function),u="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[n]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),s=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var s=this._keys.length,i=r+1;i<s;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[n]=function(){return this.entries()},t.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(N(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return s;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}(),d="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[n]=function(){return this.keys()},e}(),g="function"==typeof WeakMap?WeakMap:function(){var e=l.create(),t=s();return function(){function e(){this._key=s()}return e.prototype.has=function(e){var t=i(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return i(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=s()},e}();function s(){var t;do{t="@@WeakMap@@"+o()}while(l.has(e,t));return e[t]=!0,t}function i(e,s){if(!r.call(e,t)){if(!s)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function n(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function o(){var e=function(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):n(t,e),t}return n(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",r=0;r<16;++r){var s=e[r];4!==r&&6!==r&&8!==r||(t+="-"),s<16&&(t+="0"),t+=s.toString(16).toLowerCase()}return t}}(),f=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),C(e)&&(e=function(){var e,r,s,i;C(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=function(e){var t=e.defineMetadata,r=e.hasOwnMetadata,s=e.getOwnMetadata,i=e.getOwnMetadataKeys,n=e.deleteMetadata,o=new g,a={isProviderFor:function(e,t){var r=o.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new d,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return a}(t.Reflect));var n=new g,o={registerProvider:a,getProvider:l,setProvider:p};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case C(r):r=t;break;case r===t:break;case C(s):s=t;break;case s===t:break;default:void 0===i&&(i=new d),i.add(t)}}function c(t,n){if(!C(r)){if(r.isProviderFor(t,n))return r;if(!C(s)){if(s.isProviderFor(t,n))return r;if(!C(i))for(var o=M(i);;){var a=L(o);if(!a)return;var c=P(a);if(c.isProviderFor(t,n))return H(o),c}}}if(!C(e)&&e.isProviderFor(t,n))return e}function l(e,t){var r,s=n.get(e);return C(s)||(r=s.get(t)),C(r)?(C(r=c(e,t))||(C(s)&&(s=new u,n.set(e,s)),s.set(t,r)),r):r}function h(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function p(e,t,r){if(!h(r))throw new Error("Metadata provider not registered.");var s=l(e,t);if(s!==r){if(!C(s))return!1;var i=n.get(e);C(i)&&(i=new u,n.set(e,i)),i.set(t,r)}return!0}}()),!C(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),y=function(e){var t=new g,r={isProviderFor:function(e,r){var s=t.get(e);return!C(s)&&s.has(r)},OrdinaryDefineOwnMetadata:function(e,t,r,i){s(r,i,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,r){var i=s(t,r,!1);return!C(i)&&_(i.has(e))},OrdinaryGetOwnMetadata:function(e,t,r){var i=s(t,r,!1);if(!C(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var r=[],i=s(e,t,!1);if(C(i))return r;for(var n=M(i.keys()),o=0;;){var a=L(n);if(!a)return r.length=o,r;var c=P(a);try{r[o]=c}catch(e){try{H(n)}finally{throw e}}o++}},OrdinaryDeleteMetadata:function(e,r,i){var n=s(r,i,!1);if(C(n))return!1;if(!n.delete(e))return!1;if(0===n.size){var o=t.get(r);C(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}};return p.registerProvider(r),r;function s(s,i,n){var o=t.get(s),a=!1;if(C(o)){if(!n)return;o=new u,t.set(s,o),a=!0}var c=o.get(i);if(C(c)){if(!n)return;if(c=new u,o.set(i,c),!e.setProvider(s,i,r))throw o.delete(i),a&&t.delete(s),new Error("Wrong provider for target.")}return c}}(p);function m(e,t,r){if(b(e,t,r))return!0;var s=K(t);return!k(s)&&m(e,s,r)}function b(e,t,r){var s=V(t,r,!1);return!C(s)&&_(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(b(e,t,r))return I(e,t,r);var s=K(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=V(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){V(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=K(e);if(null===s)return r;var i=w(s,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var n=new d,o=[],a=0,c=r;a<c.length;a++){var l=c[a];n.has(l)||(n.add(l),o.push(l))}for(var h=0,u=i;h<u.length;h++)l=u[h],n.has(l)||(n.add(l),o.push(l));return o}function S(e,t){var r=V(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function E(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function C(e){return void 0===e}function k(e){return null===e}function x(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(E(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",s=D(e,i);if(void 0!==s){var n=s.call(e,r);if(x(n))throw new TypeError;return n}return function(e,t){if("string"===t){var r=e.toString;if(U(r)&&!x(i=r.call(e)))return i;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i}else{var s;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i;var i,n=e.toString;if(U(n)&&!x(i=n.call(e)))return i}throw new TypeError}(e,"default"===r?"number":r)}function _(e){return!!e}function R(e){var t=B(e,3);return"symbol"==typeof t?t:function(e){return""+e}(t)}function O(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function U(e){return"function"==typeof e}function T(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function D(e,t){var r=e[t];if(null!=r){if(!U(r))throw new TypeError;return r}}function M(e){var t=D(e,n);if(!U(t))throw new TypeError;var r=t.call(e);if(!x(r))throw new TypeError;return r}function P(e){return e.value}function L(e){var t=e.next();return!t.done&&t}function H(e){var t=e.return;t&&t.call(e)}function K(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===h)return t;if(t!==h)return t;var r=e.prototype,s=r&&Object.getPrototypeOf(r);if(null==s||s===Object.prototype)return t;var i=s.constructor;return"function"!=typeof i||i===e?t:i}function V(e,t,r){var s=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function Q(e){return e.__=void 0,delete e.__,e}e("decorate",function(e,t,r,s){if(C(r)){if(!O(e))throw new TypeError;if(!T(t))throw new TypeError;return function(e,t){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t);if(!C(s)&&!k(s)){if(!T(s))throw new TypeError;t=s}}return t}(e,t)}if(!O(e))throw new TypeError;if(!x(t))throw new TypeError;if(!x(s)&&!C(s)&&!k(s))throw new TypeError;return k(s)&&(s=void 0),function(e,t,r,s){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t,r,s);if(!C(n)&&!k(n)){if(!x(n))throw new TypeError;s=n}}return s}(e,t,r=R(r),s)}),e("metadata",function(e,t){return function(r,s){if(!x(r))throw new TypeError;if(!C(s)&&!function(e){switch(E(e)){case 3:case 4:return!0;default:return!1}}(s))throw new TypeError;v(e,t,r,s)}}),e("defineMetadata",function(e,t,r,s){if(!x(r))throw new TypeError;return C(s)||(s=R(s)),v(e,t,r,s)}),e("hasMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),m(e,t,r)}),e("hasOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),b(e,t,r)}),e("getMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),A(e,t,r)}),e("getOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),I(e,t,r)}),e("getMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),w(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),S(e,t)}),e("deleteMetadata",function(e,t,r){if(!x(t))throw new TypeError;if(C(r)||(r=R(r)),!x(t))throw new TypeError;C(r)||(r=R(r));var s=V(t,r,!1);return!C(s)&&s.OrdinaryDeleteMetadata(e,t,r)})}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))},928:e=>{e.exports=t(import.meta.url)("path")},951:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Pool=void 0;const s=r(412),i=r(516);class n{constructor(e){this.backingSet=new o,e.forEach(e=>{this.backingSet.add(e)})}static fromIP(e){let t=e.map(e=>s.RangedSet.fromSingleIP(e));return new n(t)}static fromRangeSet(e){return new n(e)}static fromCidrRanges(e){let t=e.map(e=>e.toRangeSet());return new n(t)}getRanges(){return this.backingSet.asArray()}aggregate(){let e=this.backingSet.asArray().reduce((e,t,r,s)=>{if(0==e.length)return e.push(t),e;{let r=e.pop(),s=r.toCidrRange(),i=t.toCidrRange();if(s.isCidrMergeable(i)){let t=s.merge(i);return e.push(t.toRangeSet()),e}return r.contains(t)?e.push(r):(e.push(r),e.push(t)),e}},[]),t=n.fromRangeSet(e);return t.getRanges().length!==this.getRanges().length?t.aggregate():t}getCidrRange(e){if(e.toRangeSize()>this.getSize())throw new Error(`Not enough IP number in the pool for requested prefix: ${e}`);let t,r;e:for(let s of this.getRanges())for(let i=0n;i+e.toRangeSize()<=s.getSize();i+=1n)try{let r=s.takeSubRange(i,e.toRangeSize());t=r.toCidrRange();let n=s.difference(r);this.removeExact(s),this.add(n);break e}catch(e){if(e instanceof RangeError)continue e;r=e}if(t)return t;throw void 0===r?new Error(`No range big enough in the pool for requested prefix: ${e}`):r}getCidrRanges(e){if(e.toRangeSize()>this.getSize())throw new Error("Prefix greater than pool");let t=(e,r,s)=>{try{let i=this.getCidrRange(r);s.push(i);let n=s.reduce((e,t)=>e+t.getSize(),0n);return e.toRangeSize()===n?s:t(e,r,s)}catch(n){let o=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,o,s)}};return t(e,e,[])}getSize(){return this.aggregate().getRanges().reduce((e,t)=>e+t.getSize(),0n)}resetWith(e){this.backingSet.clear(),this.backingSet=this.backingSet.add(e)}removeExact(e){let t=this.backingSet.removeExact(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}removeOverlapping(e){let t=this.backingSet.removeOverlapping(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}add(e){this.backingSet=this.backingSet.add(e)}clear(){this.backingSet.clear()}}t.Pool=n;class o{constructor(e){this.backingArray=e?this.sortArray(e):new Array}sortArray(e){return e.sort((e,t)=>e.isLessThan(t)?-1:e.isGreaterThan(t)?1:0),e}asArray(){return this.backingArray}isEquals(e){return this.backingArray.length===e.asArray().length&&this.backingArray.every((t,r)=>t.getSize()===e.asArray()[r].getSize())}add(e){let t=this.backingArray;return"push"in e?t=t.concat(e):t.push(e),new o(this.sortArray(t))}removeExact(e){let t=this.backingArray.filter(t=>"push"in e?void 0!==e.find(e=>e.isEquals(t)):!e.isEquals(t));return new o(this.sortArray(t))}removeOverlapping(e){let t=this.backingArray.flatMap(t=>{if("push"in e)return e.flatMap(e=>t.contains(e)?t.difference(e):t.inside(e)?new Array:t.isOverlapping(e)?[t.subtract(e)]:[e]);try{return t.difference(e)}catch(e){return t}});return new o(this.sortArray(t))}clear(){this.backingArray=[]}}},984:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hexadectetNotationToBinaryString=t.binaryStringToHexadecimalString=t.colonHexadecimalNotationToBinaryString=t.hexadecimalStringToHexadecatetString=t.hexadecimalStringToBinaryString=t.bigIntToHexadecimalString=void 0;const s=r(872),i=r(8);t.bigIntToHexadecimalString=e=>e.toString(16),t.hexadecimalStringToBinaryString=e=>BigInt(`0x${e}`).toString(2),t.hexadecimalStringToHexadecatetString=e=>{let r=t.hexadecimalStringToBinaryString(e);if(r.length>16)throw new Error("Given decimal in binary contains digits greater than an Hexadecatet");return i.leftPadWithZeroBit(r,16)},t.colonHexadecimalNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(t.hexadecimalStringToHexadecatetString(r)),""),t.binaryStringToHexadecimalString=e=>BigInt(`0b${e}`).toString(16),t.hexadectetNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(i.leftPadWithZeroBit(t.hexadecimalStringToBinaryString(r),16)),"")}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e].call(r.exports,r,r.exports,o),r.exports}o.m=i,o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.b=new URL("./",import.meta.url);var a={};o.r(a),o.d(a,{Any:()=>cm,BaseBlock:()=>wp,BaseStringBlock:()=>Ep,BitString:()=>wy,BmpString:()=>Fy,Boolean:()=>by,CharacterString:()=>em,Choice:()=>lm,Constructed:()=>gy,DATE:()=>sm,DateTime:()=>nm,Duration:()=>om,EndOfContent:()=>py,Enumerated:()=>By,GeneralString:()=>Xy,GeneralizedTime:()=>rm,GraphicString:()=>Yy,HexBlock:()=>yp,IA5String:()=>Jy,Integer:()=>xy,Null:()=>yy,NumericString:()=>jy,ObjectIdentifier:()=>Oy,OctetString:()=>Iy,Primitive:()=>cy,PrintableString:()=>qy,RawData:()=>um,RelativeObjectIdentifier:()=>Ny,Repeated:()=>hm,Sequence:()=>Dy,Set:()=>My,TIME:()=>am,TeletexString:()=>zy,TimeOfDay:()=>im,UTCTime:()=>tm,UniversalString:()=>$y,Utf8String:()=>Vy,ValueBlock:()=>bp,VideotexString:()=>Wy,ViewWriter:()=>Yf,VisibleString:()=>Zy,compareSchema:()=>dm,fromBER:()=>hy,verifySchema:()=>gm});const c=t(import.meta.url)("node:url");var l,h;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(l||(l={}));class u{value;constructor(e){this.value=e}static Less=new u(l.Less);static Greater=new u(l.Greater);static Equal=new u(l.Equal);isLess(){return this.value===l.Less}isGreater(){return this.value===l.Greater}isEqual(){return this.value===l.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}!function(e){e.V0_6_4="0.6.4",e.V0_6_5="0.6.5",e.V0_6_6="0.6.6",e.V0_6_7="0.6.7",e.V0_7_0="0.7.0"}(h||(h={}));const d=[h.V0_6_4,h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0],g=h.V0_6_5;let f=function(e){if(void 0===e)return;const t=e;if(!Object.values(h).includes(t))throw new Error(`Configured environment variable GP_VERSION is unknown: '${e}'. Use one of: ${d}`);return t}(process.env.GP_VERSION);class p{static override(e){f=e}static is(...e){return void 0===f?e.includes(g):e.includes(f)}static isGreaterOrEqual(e){const t=d.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${d}`);return p.is(...d.slice(t))}}function y(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function m(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function b(e){throw new Error(`Unexpected value: ${e}`)}function A(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function I(e){const t=e=>e.split("\n").map(e=>` ${e}`).join("\n").trim();if(null===e)return"<null>";if(void 0===e)return"<undefined>";if(Array.isArray(e))return`[${e.map(e=>I(e))}]`;if(e instanceof Map)return I(Array.from(e.entries()));if("number"==typeof e)return`${e} (0x${e.toString(16)})`;if("object"!=typeof e)return`${e}`;if("toString"in e&&Object.prototype.toString!==e.toString&&w.prototype.toString!==e.toString)return`${e}`;const r=e.constructor.name;let s="Object"!==r?`${r} {`:"{";const i=Object.keys(e),n=i.length<3;for(const r of i)"string"==typeof r&&(s+=n?"":"\n ",s+=`${r}: ${t(I(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const v="undefined"==typeof process?e=>{const t=performance.now();return()=>`${e} took ${performance.now()-t}ms`}:e=>{const t=process.hrtime.bigint();return()=>{const r=process.hrtime.bigint()-t,s=Number(r/1000000n).toFixed(2);return`${e} took ${s}ms`}};class w{toString(){return I(this)}}function S(e){return e}function E(e){return e}const C=Symbol("ok");class k{kind;error;enumMapping;constructor(e,t,r){this.kind=e,this.error=t,this.enumMapping=r}toString(){const e=Object.keys(this.enumMapping).find(e=>this.enumMapping[e]===this.kind)??"?";return`${e} (${this.kind}) - ${x(this.error)}`}}const x=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof k?e.toString():`${e.kind} - ${x(e.error)}`:`${e}`;var t};function B(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${x(e.error)}`}const _={ok:e=>(y(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(y(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>_.error(new k(t,r.error,e),r.details)},R=(t(import.meta.url)("node:assert"),Symbol("compare via string"));class O{[R]=!0;raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=K?String.fromCharCode(e+M-K):String.fromCharCode(e+N);let r="0x";for(const s of e)r+=t(s>>>4),r+=t(15&s);return r}(this.raw)}toJSON(){return this.toString()}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&Q(this.raw,e.raw)}compare(e){const t=Math.min(this.length,e.length),r=this.raw,s=e.raw;for(let e=0;e<t;e++){if(r[e]<s[e])return u.Less;if(r[e]>s[e])return u.Greater}return this.length<e.length?u.Less:this.length>e.length?u.Greater:u.Equal}static empty(){return new O(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return O.blobFrom(t.encode(e))}static blobFrom(e){return new O(e)}static blobFromParts(e,...t){const r=e instanceof Uint8Array?[e]:e,s=r.reduce((e,t)=>e+t.length,0)+t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(s);let n=0;for(const e of r)i.set(e,n),n+=e.length;for(const e of t)i.set(e,n),n+=e.length;return new O(i)}static blobFromNumbers(e){y(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new O(t)}static parseBlobNoPrefix(e){const t=e.length;if(t%2==1)throw new Error(`Odd number of nibbles. Invalid hex string: ${e}.`);const r=new ArrayBuffer(t/2),s=new Uint8Array(r);for(let r=0;r<t-1;r+=2){const t=e.substring(r,r+2);s[r/2]=T(t)}return new O(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return O.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield O.blobFrom(this.raw.subarray(t,t+e))}}class U extends O{length;constructor(e,t){super(e),y(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new U(e,t)}static fromNumbers(e,t){y(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new U(r,t)}static zero(e){return new U(new Uint8Array(e),e)}static fill(e,t){y((255&t)===t,"Input has to be a byte.");const r=U.zero(e);return r.raw.fill(t,0,e),r}static parseBytesNoPrefix(e,t){if(e.length>2*t)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2}`);const r=O.parseBlobNoPrefix(e);return new U(r.raw,t)}static parseBytes(e,t){if(e.length>2*t+2)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2-1}`);const r=O.parseBlob(e);return new U(r.raw,t)}isEqualTo(e){return y(this.length===e.length,"Comparing incorrectly typed bytes!"),Q(this.raw,e.raw)}asOpaque(){return this}}function T(e){return y(2===e.length,"Two-character string expected"),V(e.charCodeAt(0))<<4|V(e.charCodeAt(1))}const N="0".charCodeAt(0),D="9".charCodeAt(0),M="a".charCodeAt(0),P="f".charCodeAt(0),L="A".charCodeAt(0),H="F".charCodeAt(0),K=10;function V(e){if(e>=N&&e<=D)return e-N;if(e>=M&&e<=P)return e-M+K;if(e>=L&&e<=H)return e-L+K;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function Q(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const F=(e,t)=>e.compare(t);class G{data;bitLength;static fromBlob(e,t){return new G(e,t)}static fromBytes(e,t){return new G(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new G(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,y(8*e.length>=t,`Not enough bytes in the data array. Need ${8*e.length} has ${t}.`),this.byteLength=Math.ceil(t/8)}get raw(){return this.data.subarray(0,this.byteLength)}sumWith(e){y(e.bitLength===this.bitLength,`Invalid bit length for sumWith: ${e.bitLength} vs ${this.bitLength}`);const t=e.raw;for(let e=0;e<this.byteLength;e++)this.data[e]|=t[e]}setBit(e,t){y(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const r=Math.floor(e/8),s=1<<e%8;t?this.data[r]|=s:this.data[r]&=~s}isSet(e){y(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const t=Math.floor(e/8),r=1<<e%8;return(this.data[t]&r)>0}*indicesOfSetBits(){for(let e=0;e<this.bitLength;e++){const t=e>>3,r=e-(t<<3);1&~(this.data[t]>>r)||(yield e)}}}const $=Symbol("no key");function j(e,t,r="<root>"){const s=typeof e;if("string"===t){if("string"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("number"===t){if("number"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("boolean"===t){if("boolean"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if(Array.isArray(t)){const s=t[0];if("array"===s){const s=t[1];if("function"==typeof s)return s(e,r);if(!Array.isArray(e))throw new Error(`[${r}] Expected array, got ${e}`);const i=e,n=[];for(const[e,t]of i.entries())n[e]=j(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:j(e,t[1],r);if("object"===s)return q(t[1],e,r);if("string"===s)return q(t[1],j(e,s,r),r);if("number"===s){const s=t[0];return q(t[1],j(e,s,r),r)}throw new Error(`[${r}] Invalid parser type: ${s}`)}if("object"!==s)throw new Error(`[${r}] Expected complex type but got ${s}`);if("object"!=typeof t)throw new Error(`[${r}] Unhandled type ${t}`);if(null===e)throw new Error(`[${r}] Unexpected 'null'`);const i={},n=e,o=t;for(const e of Object.keys(n))i[e]=void 0;for(const e of Object.keys(t))if(e in n){const t=n[e];i[e]=j(t,o[e],`${r}.${e}`)}else Array.isArray(o[e])&&"optional"===o[e][0]&&(i[e]=$);const a=function(e,t){const r=Object.keys(e),s=Object.keys(t);r.sort(),s.sort();const i={},n=Math.max(s.length,s.length);for(let e=0;e<n;e++)i[r[e]]=(i[r[e]]||0)+1,i[s[e]]=(i[s[e]]||0)+2;const o=[],a=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&o.push(1===t?[a(e),a(void 0)]:[a(void 0),a(e)]);return o}(i,t);if(a.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${a.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===$&&delete i[e];return i}function q(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var z;!function(e){function t(e){return["number",e]}function r(e){return["object",e]}e.fromString=function(e){return["string",e]},e.fromNumber=t,e.castNumber=function(){return t(e=>e)},e.fromAny=r,e.optional=function(e){return["optional",e]},e.nullable=function(e){return["optional",e]},e.array=function(e){return["array",e]},e.record=function(e){return r((t,r)=>{if("object"!=typeof t||null===t)throw new Error("Expected object record for parsing");const s={};for(const[i,n]of Object.entries(t))s[i]=j(n,e,`${r}.${i}`);return s})},e.map=function(e,t){return r((r,s)=>{if("object"!=typeof r||null===r)throw new Error("Expected map for parsing");const i=new Map;for(const[n,o]of Object.entries(r))i.set(j(n,e,`${s}.key`),j(o,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=j(r,e,s);return t(i)})}}(z||(z={}));const W=e=>m(e,J(e),`input must have one-byte representation, got ${e}`),J=e=>(255&e)===e,Y=e=>m(e,Z(e),`input must have two-byte representation, got ${e}`),Z=e=>(65535&e)===e,X=e=>m(e,ee(e),`input must have four-byte representation, got ${e}`),ee=e=>(4294967295&e)>>>0===e,te=e=>{const t=BigInt(e);return m(t,re(t),`input must have eight-byte representation, got ${e}`)},re=e=>(18446744073709551615n&e)===e;function se(...e){let t=0n;for(const r of e)t+=r;const r=!re(t);return t&=0xffffffffffffffffn,{overflow:r,value:te(t)}}function ie(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function ne(e){return y(4===e.length,"Input must be a Uint8Array of length 4"),e[0]|e[1]<<8|e[2]<<16|e[3]<<24}const oe=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class ae{source;offset;context;static fromBytesBlob(e,t){return new ae(e.raw,t)}static fromBlob(e){return new ae(e)}static decodeObject(e,t,r){const s=t instanceof O?ae.fromBytesBlob(t):ae.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof O?ae.fromBytesBlob(t):ae.fromBlob(t);s.attachContext(r);const i=[];for(;s.bytesRead()<s.source.length;)i.push(s.object(e));return s.finish(),i}dataView;constructor(e,t=0,r){this.source=e,this.offset=t,this.context=r,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}clone(){return new ae(this.source,this.offset,this.context)}bytesRead(){return this.offset}remainingBytes(){const e=this.source.subarray(this.offset),t=e.length;return this.offset+=t,U.fromBlob(e,t)}i8(){return this.getNum(1,()=>this.dataView.getInt8(this.offset))}u8(){return this.getNum(1,()=>this.dataView.getUint8(this.offset))}i16(){return this.getNum(2,()=>this.dataView.getInt16(this.offset,!0))}u16(){return this.getNum(2,()=>this.dataView.getUint16(this.offset,!0))}i24(){const e=this.u24();return e>=2**23?e-2**24:e}u24(){return this.getNum(3,()=>{let e=this.dataView.getUint8(this.offset);return e|=this.dataView.getUint16(this.offset+1,!0)<<8,e})}i32(){return this.getNum(4,()=>this.dataView.getInt32(this.offset,!0))}u32(){return this.getNum(4,()=>this.dataView.getUint32(this.offset,!0))}i64(){return this.getNum(8,()=>this.dataView.getBigInt64(this.offset,!0))}u64(){return this.getNum(8,()=>this.dataView.getBigUint64(this.offset,!0))}bool(){const e=this.u8();if(0===e)return!1;if(1===e)return!0;throw new Error(`Unexpected number when decoding a boolean: ${e}`)}varU32(){this.ensureHasBytes(1);const e=this.source[this.offset],t=le(e);if(this.offset+=1,0===t)return e;if(t>4)throw new Error(`Unexpectedly large value for u32. l=${t}`);this.ensureHasBytes(t);const r=e+2**(8-t)-256<<8*t;if(1===t)return r+this.u8();if(2===t)return r+this.u16();if(3===t)return r+this.u24();if(0===r)return this.u32();throw new Error(`Unexpectedly large value for u32. l=${t}, mostSignificantByte=${r}`)}varU64(){this.ensureHasBytes(1);const e=this.source[this.offset],t=le(e);if(this.offset+=1,0===t)return te(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return te(this.dataView.getBigUint64(this.offset-t,!0));let r=BigInt(e+2**(8-t)-256)<<BigInt(8*t);for(let e=0;e<t;e+=1)r|=BigInt(this.source[this.offset-t+e])<<BigInt(8*e);return te(r)}bytes(e){if(0===e)return U.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,U.fromBlob(t,e)}bytesBlob(){const e=this.varU32();this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,O.blobFrom(t)}bitVecFixLen(e){if(0===e)return G.empty(0);const t=Math.ceil(e/8),r=this.bytes(t),s=e%8;if(s>0&&r.raw[t-1]>>s>0)throw new Error("Non-zero bits found in the last byte of bitvec encoding.");return G.fromBytes(r,e)}bitVecVarLen(){const e=this.varU32();return this.bitVecFixLen(e)}object(e){return e.decode(this)}optional(e){return this.bool()?e.decode(this):null}sequenceFixLen(e,t){const r=Array(t);for(let s=0;s<t;s+=1)r[s]=e.decode(this);return r}sequenceVarLen(e){const t=this.varU32();return this.sequenceFixLen(e,t)}resetTo(e){this.offset<e?this.skip(e-this.offset):(y(e>=0,"The offset has to be positive"),this.offset=e)}skip(e){this.ensureHasBytes(e),this.offset+=e}finish(){if(this.offset<this.source.length)throw new Error(`Expecting end of input, yet there are still ${this.source.length-this.offset} bytes left.`)}getNum(e,t){this.ensureHasBytes(e);const r=t();return this.offset+=e,r}ensureHasBytes(e){if(y(e>=0,"Negative number of bytes given."),this.offset+e>this.source.length)throw new Error(`Attempting to decode more data than there is left. Need ${e}, left: ${this.source.length-this.offset}.`)}}const ce=[255,254,252,248,240,224,192,128];function le(e){y(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<ce.length;t++)if(e>=ce[t])return 8-t;return 0}function he(e){return y(e.isExact,"The value is not exact size estimation!"),e.bytes}function ue(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const de=10485760;class ge{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new ge(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(de,t),{maxByteLength:de}),s=new Uint8Array(r);return new ge(s,r)}static encodeObject(e,t,r){const s=ge.create({expectedLength:e.sizeHint.bytes||512});return s.attachContext(r),s.object(e,t),s.viewResult()}offset=0;context;dataView;constructor(e,t){this.destination=e,this.buffer=t,this.dataView=void 0!==t?new DataView(t):new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}viewResult(){return O.blobFrom(this.destination.subarray(0,this.offset))}i32(e){this.prepareIntegerN(e,4),this.dataView.setInt32(this.offset,e,!0),this.offset+=4}i64(e){const t=2n**64n;y(e<t,"Only for numbers up to 2**64 - 1"),y(-e<=t/2n,"Only for numbers down to -2**63"),this.ensureBigEnough(8),this.dataView.setBigInt64(this.offset,e,!0),this.offset+=8}i24(e){this.prepareIntegerN(e,3),this.dataView.setInt8(this.offset,255&e),this.dataView.setInt16(this.offset+1,e>>8,!0),this.offset+=3}i16(e){this.prepareIntegerN(e,2),this.dataView.setInt16(this.offset,e,!0),this.offset+=2}i8(e){this.prepareIntegerN(e,1),this.dataView.setInt8(this.offset,e),this.offset+=1}bool(e){this.varU32(X(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);y(e<r,`Only for numbers up to 2**${8*t} - 1`),y(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){y(e>=0,"Only for natural numbers."),y(e<2**32,"Only for numbers up to 2**32"),this.varU64(BigInt(e))}varU64(e){const t=BigInt(e);if(0n===t)return this.ensureBigEnough(1),this.destination[this.offset]=0,void(this.offset+=1);let r=2n**56n;if(t>=r)return this.ensureBigEnough(9),this.destination[this.offset]=255,this.dataView.setBigUint64(this.offset+1,t,!0),void(this.offset+=9);let s=r>>7n;for(let e=7;e>=0;e-=1){if(t>=s){this.ensureBigEnough(e+1);const r=2n**BigInt(8*e),s=BigInt(256-2**(8-e))+t/r;this.destination[this.offset]=255&Number(s),this.offset+=1;let i=t%r;for(let t=this.offset;t<this.offset+e;t+=1)this.destination[t]=Number(0xffn&i),i>>=8n;return void(this.offset+=e)}r=s,s>>=7n}throw new Error(`Unhandled number encoding: ${t}`)}bytesBlob(e){this.blob(e.raw)}blob(e){this.varU32(X(e.length)),this.ensureBigEnough(e.length),this.destination.set(e,this.offset),this.offset+=e.length}bytes(e){this.ensureBigEnough(e.length),this.destination.set(e.raw,this.offset),this.offset+=e.length}bitVecFixLen(e){const t=e.raw;this.bytes(U.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(X(t)),this.bitVecFixLen(e)}object(e,t){this.applySizeHint(e),e.encode(this,t)}optional(e,t){const r=null!=t;this.bool(r),r&&(this.applySizeHint(e),e.encode(this,t))}sequenceFixLen(e,t){this.applySizeHint(e,t.length);for(const r of t)e.encode(this,r)}sequenceVarLen(e,t){y(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(X(t.length)),this.sequenceFixLen(e,t)}applySizeHint(e,t=1){const r=e.sizeHint.bytes;r>0&&t>0&&this.ensureBigEnough(r*t,{silent:!0})}ensureBigEnough(e,t={silent:!1}){y(e>=0,"Negative length given");const r=this.offset+e;if(r>de){if(t.silent)return;throw new Error("The encoded size would reach the maximum of 10485760.")}if(r>this.destination.length){if(void 0!==this.buffer){const e=Math.max(r,this.buffer.byteLength<<1);this.buffer.resize(Math.min(de,e))}if(r>this.destination.length){if(t.silent)return;throw new Error(`Not enough space in the destination array. Needs ${r}, has ${this.destination.length}.`)}}}}class fe{decoder;constructor(e){this.decoder=e}u64=()=>this.decoder.skip(8);u32=()=>this.decoder.skip(4);u24=()=>this.decoder.skip(3);u16=()=>this.decoder.skip(2);u8=()=>this.decoder.skip(1);bool=()=>this.decoder.skip(1);varU32=()=>this.varU64();varU64(){const e=le(this.decoder.u8());this.decoder.skip(e)}bytes(e){this.decoder.skip(e)}bytesBlob(){const e=this.decoder.varU32();this.decoder.skip(e)}bitVecFixLen(e){this.decoder.skip(Math.ceil(e/8))}bitVecVarLen(){const e=this.decoder.varU32();this.bitVecFixLen(e)}object(e){e.skip(this)}optional(e){this.decoder.bool()&&e.skip(this)}sequenceFixLen(e,t){for(let r=0;r<t;r+=1)e.skip(this)}sequenceVarLen(e){const t=this.decoder.varU32();return this.sequenceFixLen(e,t)}}function pe(e,t,r){if(t<e.minLength)throw new Error(`${r}: length is below minimal. ${t} < ${e.minLength}`);if(t>e.maxLength)throw new Error(`${r}: length is above maximal. ${t} > ${e.maxLength}`)}class ye{getView;getValue;getEncoded;cachedValue;cachedView;cachedBlob;constructor(e,t,r){this.getView=e,this.getValue=t,this.getEncoded=r}materialize(){return void 0===this.cachedValue&&(this.cachedValue=this.getValue()),this.cachedValue}view(){return void 0===this.cachedView&&(this.cachedView=this.getView()),this.cachedView}encoded(){return void 0===this.cachedBlob&&(this.cachedBlob=this.getEncoded()),this.cachedBlob}}class me{decoder;materializedConstructor;descriptors;descriptorsKeys;cache=new Map;initialDecoderOffset;lastDecodedFieldIdx=-1;constructor(e,t,r){this.decoder=e,this.materializedConstructor=t,this.descriptors=r,this.descriptorsKeys=Object.keys(r),this.initialDecoderOffset=e.bytesRead()}materialize(){const e=this.descriptorsKeys,t=Object.fromEntries(e.map(e=>[e,this.get(e).materialize()]));return this.materializedConstructor.create(t)}encoded(){const e=this.descriptorsKeys;if(0===e.length)return O.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return O.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead()))}get(e){const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}decodeUpTo(e){const t=this.descriptorsKeys.indexOf(e),r=this.descriptorsKeys[this.lastDecodedFieldIdx];y(this.lastDecodedFieldIdx<t,`Unjustified call to 'decodeUpTo' -\n the index ($Blobindex}, ${String(e)})\n is already decoded (${this.lastDecodedFieldIdx}, ${String(r)}).\n `);let s=this.cache.get(r);const i=new fe(this.decoder);for(let e=this.lastDecodedFieldIdx+1;e<=t;e++){const t=i.decoder.clone(),r=this.descriptorsKeys[e],n=this.descriptors[r];s=new ye(()=>n.View.decode(t.clone()),()=>n.decode(t.clone()),()=>n.skipEncoded(t.clone())),n.skip(i),this.cache.set(r,s),this.lastDecodedFieldIdx=e}return m(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class be{decoder;descriptor;length;cache=new Map;initialDecoderOffset;lastDecodedIdx=-1;constructor(e,t,r){this.decoder=e,this.descriptor=t,this.initialDecoderOffset=this.decoder.bytesRead(),this.length=r??e.varU32()}*[Symbol.iterator](){for(let e=0;e<this.length;e++){const t=this.get(e),r=m(t,void 0!==t,"We are within 0..this.length so all items are defined.");yield r}}map(e){const t=new Array(this.length);let r=0;for(const s of this)t[r]=e(s),r++;return t}get(e){if(e>=this.length)return;const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}encoded(){return 0===this.length?O.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),O.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){y(this.lastDecodedIdx<e,`Unjustified call to 'decodeUpTo' - the index (${e}) is already decoded (${this.lastDecodedIdx}).`);let t=this.cache.get(this.lastDecodedIdx);const r=new fe(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new ye(()=>i.View.decode(e.clone()),()=>i.decode(e.clone()),()=>i.skipEncoded(e.clone())),i.skip(r),this.cache.set(s,t),this.lastDecodedIdx=s}return m(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Ae{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Ae(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Ae(e,t,r,s,i,null)}constructor(e,t,r,s,i,n){this.name=e,this.sizeHint=t,this.encode=r,this.decode=s,this.skip=i,this.View=n??this}skipEncoded(e){const t=e.bytesRead();this.skip(new fe(e));const r=e.bytesRead();return O.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Ae(this.name,this.sizeHint,(t,r)=>this.encode(t,e(r)),e=>t(this.decode(e)),this.skip,this.View)}asOpaque(){return this.convert(e=>e,e=>e)}}function Ie(e){return e.convert(e=>(y(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function ve(e){return{bytes:e,isExact:!0}}var we,Se;function Ee(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function Ce(e){return e.View!==e}(Se=we||(we={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Ae.new(`Bytes<${t}>`,ve(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),Se.varU32=Ae.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),Se.varU64=Ae.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),Se.u64=Ae.withView("u64",ve(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),Se.bytes(8)),Se.u32=Ae.withView("u32",ve(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),Se.bytes(4)),Se.u24=Ae.withView("u24",ve(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),Se.bytes(3)),Se.u16=Ae.withView("u16",ve(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),Se.bytes(2)),Se.u8=Ae.new("u8",ve(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),Se.i64=Ae.withView("u64",ve(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),Se.bytes(8)),Se.i32=Ae.withView("i32",ve(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),Se.bytes(4)),Se.i24=Ae.withView("i24",ve(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),Se.bytes(3)),Se.i16=Ae.withView("i16",ve(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),Se.bytes(2)),Se.i8=Ae.new("i8",ve(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),Se.bool=Ae.new("bool",ve(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),Se.blob=Ae.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),Se.string=Ae.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(O.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),Se.blob),Se.bitVecVarLen=Ae.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),Se.bitVecFixLen=e=>Ae.new(`BitVec[${e}]`,ve(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),Se.optional=e=>{const t=Ae.new(`Optional<${e.name}>`,ue({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Ce(e)?Ae.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,Se.optional(e.View)):t},Se.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Ae.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{pe(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return pe(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return pe(t,i,r),s.sequenceFixLen(e,i)},function(e,t){const r={bytes:64*e.sizeHint.bytes,isExact:!1},s=e.name!==e.View.name?`, ${e.View.name}`:"",i=`SeqView<${e.name}${s}>[?]`,n=r=>{const s=r.decoder.varU32();return pe(t,s,i),r.sequenceFixLen(e,s)};return Ae.new(i,r,(e,r)=>{pe(t,r.length,i);const s=r.encoded();e.bytes(U.fromBlob(s.raw,s.length))},t=>{const r=new be(t.clone(),e);return n(new fe(t)),r},n)}(e,t))},Se.sequenceFixLen=(e,t)=>Ae.withView(`Sequence<${e.name}>[${t}]`,{bytes:t*e.sizeHint.bytes,isExact:e.sizeHint.isExact},(t,r)=>t.sequenceFixLen(e,r),r=>r.sequenceFixLen(e,t),r=>r.sequenceFixLen(e,t),function(e,{fixedLength:t}){const r={bytes:e.sizeHint.bytes*t,isExact:e.sizeHint.isExact},s=r=>r.sequenceFixLen(e,t),i=e.name!==e.View.name?`, ${e.View.name}`:"",n=`SeqView<${e.name}${i}>[${t}]`;return Ae.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(U.fromBlob(r.raw,r.length))},r=>{const i=new be(r.clone(),e,t);return s(new fe(r)),i},s)}(e,{fixedLength:t})),Se.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Ae.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*ue(e.sizeHint,t.sizeHint).bytes:32*(ue(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const o=Array.from(n.entries());o.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(X(o.length));for(const[r,s]of o)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,o=s??i.varU32();let a=null;for(let s=0;s<o;s+=1){const s=e.decode(i),o=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==a&&r(a,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${s}"!`);n.set(s,o),a=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return Ce(t)?Ae.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,Se.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},Se.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Ae.new(e,t,r,s,i),Se.select=({name:e,sizeHint:t},r)=>Ae.withView(e,t,(e,t)=>r(e.getContext()).encode(e,t),e=>r(e.getContext()).decode(e),e=>r(e.decoder.getContext()).skip(e),r(null).View),Se.object=(e,t="object",r=e=>e)=>Se.Class({name:t,create:r},e),Se.Class=(e,t)=>{let r=ve(0);Ee(t,(e,t)=>{r=ue(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Ee(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends me{constructor(r){super(r,e,t)}}return Ee(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Ae.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(U.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new fe(e)),t},s)}(e,t,r,s);return Ae.withView(e.name,r,(e,r)=>{Ee(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Ee(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var ke=o(405);const xe=32,Be=144,_e=144,Re=32;class Oe extends w{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ue extends Oe{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Te{emptyHash(){return U.zero(Re)}}const Ne=new Te;var De,Me=o(675),Pe=o.n(Me);function Le(e,t=Ne){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Pe()(Re);for(const t of e)s?.update(t instanceof O?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function He(e,t=Ne){const r=Pe()(Re),s=e instanceof O?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function Ke(e,t=Ne){return He(O.blobFromString(e),t)}function Ve(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Qe{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return Ve(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Fe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Ge=null!==(De=Fe.Buffer)&&void 0!==De?De:null,$e=Fe.TextEncoder?new Fe.TextEncoder:null;function je(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const qe="a".charCodeAt(0)-10,ze="0".charCodeAt(0);function We(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+qe:r+ze,r=15&t[i],e[s++]=r>9?r+qe:r+ze}return String.fromCharCode.apply(null,e)}const Je=null!==Ge?e=>{if("string"==typeof e){const t=Ge.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Ge.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")}:e=>{if("string"==typeof e)return $e.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},Ye=new Uint8Array(256);for(let e=0;e<64;e++)Ye["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function Ze(e){const t=function(e){let t=Math.floor(.75*e.length);const r=e.length;return"="===e[r-1]&&(t-=1,"="===e[r-2]&&(t-=1)),t}(e),r=e.length,s=new Uint8Array(t);let i=0;for(let t=0;t<r;t+=4){const r=Ye[e.charCodeAt(t)],n=Ye[e.charCodeAt(t+1)],o=Ye[e.charCodeAt(t+2)],a=Ye[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|o>>2,i+=1,s[i]=(3&o)<<6|63&a,i+=1}return s}const Xe=16384,et=new Qe,tt=new Map;function rt(e,t){return Ve(this,void 0,void 0,function*(){let r=null,s=null,i=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const n=()=>new DataView(r.exports.memory.buffer).getUint32(r.exports.STATE_SIZE,!0),o=et.dispatch(()=>Ve(this,void 0,void 0,function*(){if(!tt.has(e.name)){const t=Ze(e.data),r=WebAssembly.compile(t);tt.set(e.name,r)}const t=yield tt.get(e.name);r=yield WebAssembly.instantiate(t,{})})),a=(e=null)=>{i=!0,r.exports.Hash_Init(e)},c=e=>{if(!i)throw new Error("update() called before init()");(e=>{let t=0;for(;t<e.length;){const i=e.subarray(t,t+Xe);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(Je(e))},l=new Uint8Array(2*t),h=(e,n=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,r.exports.Hash_Final(n),"binary"===e?s.slice(0,t):We(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<Xe;let d=u;switch(e.name){case"argon2":case"scrypt":d=()=>!0;break;case"blake2b":case"blake2s":d=(e,t)=>t<=512&&u(e);break;case"blake3":d=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":d=()=>!1}return yield(()=>Ve(this,void 0,void 0,function*(){r||(yield o);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,Xe)}))(),{getMemory:()=>s,writeMemory:(e,t=0)=>{s.set(e,t)},getExports:()=>r.exports,setMemorySize:e=>{r.exports.Hash_SetMemorySize(e);const t=r.exports.Hash_GetBuffer(),i=r.exports.memory.buffer;s=new Uint8Array(i,t,e)},init:a,update:c,digest:h,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),o=r.exports.memory.buffer,a=new Uint8Array(o,t,s),c=new Uint8Array(4+s);return function(e,t){const r=t.length>>1;for(let s=0;s<r;s++){const r=s<<1;e[s]=je(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(a,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),o=n(),a=4+o,c=r.exports.memory.buffer;if(t.length!==a)throw new Error(`Bad state length (expected ${a} bytes, got ${t.length})`);if(!function(e,t){if(e.length!==2*t.length)return!1;for(let r=0;r<t.length;r++){const s=r<<1;if(t[r]!==je(e.charCodeAt(s),e.charCodeAt(s+1)))return!1}return!0}(e.hash,t.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const l=t.subarray(4);new Uint8Array(c,s,o).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!d(e,i))return a(i),c(e),h("hex",n);const o=Je(e);return s.set(o),r.exports.Hash_Calculate(o.length,i,n),We(l,s,t)},hashLength:t}})}new Qe,new Qe,new DataView(new ArrayBuffer(4)),new Qe,new Qe,new Qe,new Qe,new Uint8Array(8),new Qe,new Qe,new Qe;var st={name:"sha3",data:"AGFzbQEAAAABFARgAAF/YAF/AGACf38AYAN/f38AAwgHAAEBAgEAAwUEAQECAgYOAn8BQZCNBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwABA1IYXNoX0dldFN0YXRlAAUOSGFzaF9DYWxjdWxhdGUABgpTVEFURV9TSVpFAwEKpBwHBQBBgAoL1wMAQQBCADcDgI0BQQBCADcD+IwBQQBCADcD8IwBQQBCADcD6IwBQQBCADcD4IwBQQBCADcD2IwBQQBCADcD0IwBQQBCADcDyIwBQQBCADcDwIwBQQBCADcDuIwBQQBCADcDsIwBQQBCADcDqIwBQQBCADcDoIwBQQBCADcDmIwBQQBCADcDkIwBQQBCADcDiIwBQQBCADcDgIwBQQBCADcD+IsBQQBCADcD8IsBQQBCADcD6IsBQQBCADcD4IsBQQBCADcD2IsBQQBCADcD0IsBQQBCADcDyIsBQQBCADcDwIsBQQBCADcDuIsBQQBCADcDsIsBQQBCADcDqIsBQQBCADcDoIsBQQBCADcDmIsBQQBCADcDkIsBQQBCADcDiIsBQQBCADcDgIsBQQBCADcD+IoBQQBCADcD8IoBQQBCADcD6IoBQQBCADcD4IoBQQBCADcD2IoBQQBCADcD0IoBQQBCADcDyIoBQQBCADcDwIoBQQBCADcDuIoBQQBCADcDsIoBQQBCADcDqIoBQQBCADcDoIoBQQBCADcDmIoBQQBCADcDkIoBQQBCADcDiIoBQQBCADcDgIoBQQBBwAwgAEEBdGtBA3Y2AoyNAUEAQQA2AoiNAQuMAwEIfwJAQQAoAoiNASIBQQBIDQBBACABIABqQQAoAoyNASICcDYCiI0BAkACQCABDQBBgAohAwwBCwJAIAIgAWsiBCAAIAQgAEkbIgNFDQAgA0EDcSEFQQAhBgJAIANBBEkNACABQYCKAWohByADQXxxIQhBACEGA0AgByAGaiIDQcgBaiAGQYAKai0AADoAACADQckBaiAGQYEKai0AADoAACADQcoBaiAGQYIKai0AADoAACADQcsBaiAGQYMKai0AADoAACAIIAZBBGoiBkcNAAsLIAVFDQAgAUHIiwFqIQMDQCADIAZqIAZBgApqLQAAOgAAIAZBAWohBiAFQX9qIgUNAAsLIAAgBEkNAUHIiwEgAhADIAAgBGshACAEQYAKaiEDCwJAIAAgAkkNAANAIAMgAhADIAMgAmohAyAAIAJrIgAgAk8NAAsLIABFDQBBACECQcgBIQYDQCAGQYCKAWogAyAGakG4fmotAAA6AAAgBkEBaiEGIAAgAkEBaiICQf8BcUsNAAsLC+ALAS1+IAApA0AhAkEAKQPAigEhAyAAKQM4IQRBACkDuIoBIQUgACkDMCEGQQApA7CKASEHIAApAyghCEEAKQOoigEhCSAAKQMgIQpBACkDoIoBIQsgACkDGCEMQQApA5iKASENIAApAxAhDkEAKQOQigEhDyAAKQMIIRBBACkDiIoBIREgACkDACESQQApA4CKASETQQApA8iKASEUAkACQCABQcgASw0AQQApA+iKASEVQQApA/iKASEWQQApA/CKASEXQQApA4CLASEYQQApA9CKASEZQQApA+CKASEaQQApA9iKASEbDAELQQApA+CKASAAKQNghSEaQQApA9iKASAAKQNYhSEbQQApA9CKASAAKQNQhSEZIBQgACkDSIUhFEEAKQPoigEhFUEAKQP4igEhFkEAKQPwigEhF0EAKQOAiwEhGCABQekASQ0AIBggACkDgAGFIRggFiAAKQN4hSEWIBcgACkDcIUhFyAVIAApA2iFIRUgAUGJAUkNAEEAQQApA4iLASAAKQOIAYU3A4iLAQsgAyAChSEcIAUgBIUhHSAHIAaFIQcgCSAIhSEIIAsgCoUhHiANIAyFIQkgDyAOhSEKIBEgEIUhCyATIBKFIQxBACkDuIsBIRBBACkDkIsBIRFBACkDoIsBIRJBACkDsIsBIRNBACkDiIsBIQ1BACkDwIsBIQ5BACkDmIsBIR9BACkDqIsBIQ9BwH4hAANAIB4gByALhSAbhSAYhSAPhUIBiYUgFIUgF4UgH4UgDoUhAiAMIB0gCoUgGoUgDYUgE4VCAYmFIAiFIBmFIBaFIBKFIgMgB4UhICAJIAggDIUgGYUgFoUgEoVCAYmFIByFIBWFIBGFIBCFIgQgDoUhISAcIAogFCAehSAXhSAfhSAOhUIBiYUgHYUgGoUgDYUgE4UiBYVCN4kiIiALIBwgCYUgFYUgEYUgEIVCAYmFIAeFIBuFIBiFIA+FIgYgCoVCPokiI0J/hYMgAyAPhUICiSIkhSEOIBYgAoVCKYkiJSAEIBeFQieJIiZCf4WDICKFIQ8gECAFhUI4iSIQIAYgDYVCD4kiJ0J/hYMgAyAbhUIKiSIohSENIAQgHoVCG4kiKSAoIAggAoVCJIkiKkJ/hYOFIRYgBiAdhUIGiSIrIAMgC4VCAYkiLEJ/hYMgEiAChUISiSIthSEXICsgBCAfhUIIiSIuIBUgBYVCGYkiFUJ/hYOFIRsgBiAThUI9iSIdIAQgFIVCFIkiBCAJIAWFQhyJIghCf4WDhSEUIAggHUJ/hYMgAyAYhUItiSIDhSEcIB0gA0J/hYMgGSAChUIDiSIJhSEdIAQgAyAJQn+Fg4UhByAJIARCf4WDIAiFIQggDCAChSICICFCDokiA0J/hYMgESAFhUIViSIEhSEJIAYgGoVCK4kiBSADIARCf4WDhSEKIAQgBUJ/hYMgIEIsiSIEhSELIABB0AlqKQMAIAUgBEJ/hYOFIAKFIQwgJyAoQn+FgyAqhSIFIRggAyAEIAJCf4WDhSICIR4gKiApQn+FgyAQhSIDIR8gLSAuQn+FgyAVhSIEIRogJiAkICVCf4WDhSIGIRMgFSArQn+FgyAshSIoIRkgIyAmICJCf4WDhSIiIRIgLiAsIC1Cf4WDhSImIRUgJyApIBBCf4WDhSInIREgIyAkQn+FgyAlhSIjIRAgAEEIaiIADQALQQAgDzcDqIsBQQAgBTcDgIsBQQAgGzcD2IoBQQAgBzcDsIoBQQAgCzcDiIoBQQAgDjcDwIsBQQAgAzcDmIsBQQAgFzcD8IoBQQAgFDcDyIoBQQAgAjcDoIoBQQAgBjcDsIsBQQAgDTcDiIsBQQAgBDcD4IoBQQAgHTcDuIoBQQAgCjcDkIoBQQAgIjcDoIsBQQAgFjcD+IoBQQAgKDcD0IoBQQAgCDcDqIoBQQAgDDcDgIoBQQAgIzcDuIsBQQAgJzcDkIsBQQAgJjcD6IoBQQAgHDcDwIoBQQAgCTcDmIoBC/gCAQV/QeQAQQAoAoyNASIBQQF2ayECAkBBACgCiI0BIgNBAEgNACABIQQCQCABIANGDQAgA0HIiwFqIQVBACEDA0AgBSADakEAOgAAIANBAWoiAyABQQAoAoiNASIEa0kNAAsLIARByIsBaiIDIAMtAAAgAHI6AAAgAUHHiwFqIgMgAy0AAEGAAXI6AABByIsBIAEQA0EAQYCAgIB4NgKIjQELAkAgAkEESQ0AIAJBAnYiA0EDcSEFQQAhBAJAIANBf2pBA0kNACADQfz///8DcSEBQQAhA0EAIQQDQCADQYAKaiADQYCKAWooAgA2AgAgA0GECmogA0GEigFqKAIANgIAIANBiApqIANBiIoBaigCADYCACADQYwKaiADQYyKAWooAgA2AgAgA0EQaiEDIAEgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQEgBEECdCEDA0AgA0GACmogA0GAigFqKAIANgIAIANBBGohAyABQXxqIgENAAsLCwYAQYCKAQvRBgEDf0EAQgA3A4CNAUEAQgA3A/iMAUEAQgA3A/CMAUEAQgA3A+iMAUEAQgA3A+CMAUEAQgA3A9iMAUEAQgA3A9CMAUEAQgA3A8iMAUEAQgA3A8CMAUEAQgA3A7iMAUEAQgA3A7CMAUEAQgA3A6iMAUEAQgA3A6CMAUEAQgA3A5iMAUEAQgA3A5CMAUEAQgA3A4iMAUEAQgA3A4CMAUEAQgA3A/iLAUEAQgA3A/CLAUEAQgA3A+iLAUEAQgA3A+CLAUEAQgA3A9iLAUEAQgA3A9CLAUEAQgA3A8iLAUEAQgA3A8CLAUEAQgA3A7iLAUEAQgA3A7CLAUEAQgA3A6iLAUEAQgA3A6CLAUEAQgA3A5iLAUEAQgA3A5CLAUEAQgA3A4iLAUEAQgA3A4CLAUEAQgA3A/iKAUEAQgA3A/CKAUEAQgA3A+iKAUEAQgA3A+CKAUEAQgA3A9iKAUEAQgA3A9CKAUEAQgA3A8iKAUEAQgA3A8CKAUEAQgA3A7iKAUEAQgA3A7CKAUEAQgA3A6iKAUEAQgA3A6CKAUEAQgA3A5iKAUEAQgA3A5CKAUEAQgA3A4iKAUEAQgA3A4CKAUEAQcAMIAFBAXRrQQN2NgKMjQFBAEEANgKIjQEgABACQeQAQQAoAoyNASIAQQF2ayEDAkBBACgCiI0BIgFBAEgNACAAIQQCQCAAIAFGDQAgAUHIiwFqIQVBACEBA0AgBSABakEAOgAAIAFBAWoiASAAQQAoAoiNASIEa0kNAAsLIARByIsBaiIBIAEtAAAgAnI6AAAgAEHHiwFqIgEgAS0AAEGAAXI6AABByIsBIAAQA0EAQYCAgIB4NgKIjQELAkAgA0EESQ0AIANBAnYiAUEDcSEFQQAhBAJAIAFBf2pBA0kNACABQfz///8DcSEAQQAhAUEAIQQDQCABQYAKaiABQYCKAWooAgA2AgAgAUGECmogAUGEigFqKAIANgIAIAFBiApqIAFBiIoBaigCADYCACABQYwKaiABQYyKAWooAgA2AgAgAUEQaiEBIAAgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQAgBEECdCEBA0AgAUGACmogAUGAigFqKAIANgIAIAFBBGohASAAQXxqIgANAAsLCwvYAQEAQYAIC9ABkAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAgoAAAAAAAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgA==",hash:"fb24e536"};function it(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Qe,new Qe,new Qe,new Qe,new Qe,new Qe,new Qe,new Qe,new Uint8Array(8),new Qe,new Uint8Array(8),new Qe,new Uint8Array(8),new Qe,new Qe,new Qe;class nt{hasher;static async create(){return new nt(await function(e=512){if(it(e))return Promise.reject(it(e));const t=e/8;return rt(st,t).then(r=>{r.init(e);const s={init:()=>(r.init(e),s),update:e=>(r.update(e),s),digest:e=>r.digest(e,1),save:()=>r.save(),load:e=>(r.load(e),s),blockSize:200-2*t,digestSize:t};return s})}(256))}constructor(e){this.hasher=e}}function ot(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return U.fromBlob(e.hasher.digest("binary"),Re)}class at{map=new Map;constructor(){}static new(){return new at}static fromEntries(e){const t=new at;for(const[r,s]of e)t.set(r,s);return t}get size(){return this.map.size}has(e){return this.map.has(e.toString())}get(e){return this.map.get(e.toString())?.[1]}[Symbol.iterator](){return this.map.values()}entries(){return this.map.values()}*keys(){for(const e of this.map.values())yield e[0]}*values(){for(const e of this.map.values())yield e[1]}toSortedArray(e){const t=Array.from(this.map.values());return t.sort((t,r)=>e(t[0],r[0]).value),t.map(e=>e[1])}toJSON(){return Object.fromEntries(this)}set(e,t){this.map.set(e.toString(),[e,t])}delete(e){return this.map.delete(e.toString())}}class ct{map;static viewDictionaryKeys(e){return new ct(e)}static from(e){const t=ct.new();return t.insertAll(e),t}static new(){return new ct}constructor(e=at.new()){this.map=e}get size(){return this.map.size}has(e){return this.map.has(e)}*intersection(e){const t=this.size<e.size?this:e,r=t===this?e:this;for(const e of t)r.has(e)&&(yield e)}*[Symbol.iterator](){for(const e of this.map)yield e[0]}insert(e){return this.map.set(e,!0)}insertAll(e){for(const t of e)this.map.set(t,!0)}delete(e){return this.map.delete(e)}}function lt(e){return e}class ht extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){y(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new ht(t);for(let s=0;s<t;s++)r[s]=e[s];return Object.seal(r),r}static fill(e,t){const r=[];for(let s=0;s<t;s++)r.push(e(s));return ht.new(r,t)}toString(){return I(Array.from(this))}}class ut{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new ut(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new ut([],e);const s=t.slice();for(let t=1;t<r;t++)if(e(s[t-1],s[t]).isGreater())throw new Error(`Expected sorted array, got: ${s}`);return new ut(s,e)}constructor(e,t){this.array=e,this.comparator=t}insert(e){const t=this.binarySearch(e);this.array.splice(t.idx,0,e)}pop(){return this.array.pop()}findIndex(e){const t=this.binarySearch(e);return t.isEqual?t.idx:-1}findExact(e){const t=this.binarySearch(e);if(t.isEqual)return this.array[t.idx]}removeOne(e){const t=this.binarySearch(e);t.isEqual&&this.array.splice(t.idx,1)}has(e){return this.binarySearch(e).isEqual}get length(){return this.array.length}slice(e,t){return this.array.slice(e,t)}binarySearch(e){const t=this.array,r=this.comparator;let s=0,i=t.length;for(;s<i;){const n=i+s>>1,o=r(t[n],e);if(o.isEqual())return{idx:n,isEqual:!0};o.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){y(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator,s=e.array,i=s.length,n=t.array,o=n.length,a=new Array(i+o);let c=0,l=0,h=0;for(;c<i&&l<o;)r(s[c],n[l]).isLess()?a[h++]=s[c++]:(r(s[c],n[l]).isGreater()||(a[h++]=s[c++]),a[h++]=n[l++]);for(;c<i;)a[h++]=s[c++];for(;l<o;)a[h++]=n[l++];return ut.fromSortedArray(r,a)}*[Symbol.iterator](){for(const e of this.array)yield e}}class dt extends ut{static fromArray(e,t=[]){const r=t.slice();r.sort((t,r)=>e(t,r).value);const s=r.length;for(let i=1;i<s;i++)if(e(r[i-1],r[i]).isEqual())throw new Error(`Expected array without duplicates, got: ${t}`);return new dt(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new dt([],e);const r=t.slice(),s=r.length;for(let t=1;t<s;t++)if(e(r[t-1],r[t]).isGreaterOrEqual())throw new Error(`Expected sorted array without duplicates, got: ${r}`);return new dt(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){y(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return dt.fromSortedArray(r,t.array);if(0===t.length)return dt.fromSortedArray(r,e.array);const s=ut.fromTwoSortedCollections(e,t).array,i=s.length;let n=1;for(let e=1;e<i;e++)r(s[e-1],s[e]).isNotEqual()&&(s[n++]=s[e]);return s.length=n,dt.fromSortedArray(r,s)}}class gt extends w{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;slotDuration;epochLength;rotationPeriod;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;numberECPiecesPerSegment;preimageExpungePeriod;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=Math.floor(e.validatorsCount/3),this.validatorsSuperMajority=2*Math.floor(e.validatorsCount/3)+1,this.coresCount=e.coresCount,this.slotDuration=e.slotDuration,this.epochLength=e.epochLength,this.rotationPeriod=e.rotationPeriod,this.contestLength=e.contestLength,this.ticketsPerValidator=e.ticketsPerValidator,this.maxTicketsPerExtrinsic=e.maxTicketsPerExtrinsic,this.numberECPiecesPerSegment=e.numberECPiecesPerSegment,this.preimageExpungePeriod=e.preimageExpungePeriod}}const ft=new gt({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026,preimageExpungePeriod:6}),pt=new gt({contestLength:500,coresCount:341,epochLength:600,maxTicketsPerExtrinsic:16,rotationPeriod:10,slotDuration:6,ticketsPerValidator:2,validatorsCount:1023,numberECPiecesPerSegment:6,preimageExpungePeriod:19200});class yt{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new yt(new gt(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function mt(e){const t=pt,{name:r,sizeHint:s}=e(t),i=new Map;return we.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof gt){const t=i.get(s);if(void 0!==t)return t;const r=e(s);return i.set(s,r),r}if(null===s)return e(t);if(null!==s)throw new Error(`[${r}] Unexpected context type ${typeof s} while encoding/decoding.`);throw new Error(`[${r}] Missing context while encoding/decoding!`)})}const bt=(e,t,r)=>"fixedLength"in t?Ie(we.sequenceFixLen(e,t.fixedLength)).convert(E,lt):Ie(we.sequenceVarLen(e,t)).convert(E,lt),At=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return we.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),ht.new(e,t)))},It=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Ae.new(`HashDictionary<${e.name}>[?]`,{bytes:r*e.sizeHint.bytes,isExact:!1},(t,r)=>{const i=Array.from(r.values());i.sort((e,t)=>s(e,t).value),t.varU32(X(i.length));for(const r of i)e.encode(t,r)},r=>{const i=at.new(),n=r.varU32();let o=null;for(let a=0;a<n;a+=1){const n=e.decode(r),a=t(n);if(i.has(a))throw new Error(`Duplicate item in the dictionary encoding: "${a}"!`);if(null!==o&&s(o,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${n}"!`);i.set(a,n),o=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class vt extends w{attempt;signature;static Codec=we.Class(vt,{attempt:we.u8.asOpaque(),signature:we.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new vt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class wt extends w{id;attempt;static Codec=we.Class(wt,{id:we.bytes(Re),attempt:we.u8.asOpaque()});static create({id:e,attempt:t}){return new wt(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const St=bt(vt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Et;!function(e){e.bytesN=e=>z.fromString(t=>U.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>z.fromString(t=>U.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>z.fromString(e=>U.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>z.fromString(e=>U.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=z.fromString(O.parseBlob),e.bytesBlobNoPrefix=z.fromString(O.parseBlobNoPrefix),e.ed25519Signature=z.fromString(e=>U.parseBytes(e,64).asOpaque()),e.ticketAttempt=z.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return W(e)}),e.uint8Array=z.fromAny(e=>{if(Array.isArray(e))return new Uint8Array(e);if(null===e)return new Uint8Array;throw new Error(`Expected an array, got ${typeof e} instead. [uint8Array]`)}),e.bigUint64Array=z.fromAny(e=>{if(Array.isArray(e))return new BigUint64Array(e.map(e=>BigInt(e)));if(null===e)return new BigUint64Array;throw new Error(`Expected an array, got ${typeof e} instead. [bigUint64Array]`)}),e.bigUint64=z.fromAny(e=>BigInt(e))}(Et||(Et={}));const Ct=2n**255n-19n,kt=2n**252n+27742317777372353535851937790883648493n,xt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Bt=0x6666666666666666666666666666666666666666666666666666666666666658n,_t={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Ct,n:kt,h:8,Gx:xt,Gy:Bt},Rt=(e="")=>{throw new Error(e)},Ot=e=>"string"==typeof e,Ut=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Rt("Uint8Array of valid length expected"):e,Tt=e=>new Uint8Array(e),Nt=(e,t=Ct)=>{let r=e%t;return r>=0n?r:t+r},Dt=e=>e instanceof Mt?e:Rt("Point expected");class Mt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new Mt(e.x,e.y,1n,Nt(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=_t,s=(n=e,o=32,e=Ut(Ot(n)?Qt(n):Tt(Ut(n)),o)).slice(),i=e[31];var n,o;s[31]=-129&i;const a=Gt(s);!t||0n<=a&&a<2n**256n||Rt("bad y coord 1"),t||0n<=a&&a<Ct||Rt("bad y coord 2");const c=Nt(a*a),l=Nt(c-1n),h=Nt(r*c+1n);let{isValid:u,value:d}=Wt(l,h);u||Rt("bad y coordinate 3");const g=1n==(1n&d),f=!!(128&i);return!t&&0n===d&&f&&Rt("bad y coord 3"),f!==g&&(d=Nt(-d)),new Mt(d,a,1n,Nt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{ex:t,ey:r,ez:s}=this,{ex:i,ey:n,ez:o}=Dt(e),a=Nt(t*o),c=Nt(i*s),l=Nt(r*o),h=Nt(n*s);return a===c&&l===h}is0(){return this.equals(Lt)}negate(){return new Mt(Nt(-this.ex),this.ey,this.ez,Nt(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=_t,i=Nt(e*e),n=Nt(t*t),o=Nt(2n*Nt(r*r)),a=Nt(s*i),c=e+t,l=Nt(Nt(c*c)-i-n),h=a+n,u=h-o,d=a-n,g=Nt(l*u),f=Nt(h*d),p=Nt(l*d),y=Nt(u*h);return new Mt(g,f,y,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:o,ez:a,et:c}=Dt(e),{a:l,d:h}=_t,u=Nt(t*n),d=Nt(r*o),g=Nt(i*h*c),f=Nt(s*a),p=Nt((t+r)*(n+o)-u-d),y=Nt(f-g),m=Nt(f+g),b=Nt(d-l*u),A=Nt(p*y),I=Nt(m*b),v=Nt(p*b),w=Nt(y*m);return new Mt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Rt("cannot multiply by 0"):Lt;if("bigint"==typeof e&&0n<e&&e<kt||Rt("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(Pt))return er(e).p;let r=Lt,s=Pt;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?r=r.add(i):t&&(s=s.add(i));return r}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(_t.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(kt/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(Lt))return{x:0n,y:1n};const s=jt(r,Ct);return 1n!==Nt(r*s)&&Rt("invalid inverse"),{x:Nt(e*s),y:Nt(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Ft(t);return r[31]|=1n&e?128:0,r}toHex(){return Kt(this.toRawBytes())}}Mt.BASE=new Mt(xt,Bt,1n,Nt(xt*Bt)),Mt.ZERO=new Mt(0n,1n,1n,0n);const{BASE:Pt,ZERO:Lt}=Mt,Ht=(e,t)=>e.toString(16).padStart(t,"0"),Kt=e=>Array.from(Ut(e)).map(e=>Ht(e,2)).join(""),Vt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Qt=e=>{const t="hex invalid";if(!Ot(e))return Rt(t);const r=e.length,s=r/2;if(r%2)return Rt(t);const i=Tt(s);for(let r=0,n=0;r<s;r++,n+=2){const s=Vt(e.charCodeAt(n)),o=Vt(e.charCodeAt(n+1));if(void 0===s||void 0===o)return Rt(t);i[r]=16*s+o}return i},Ft=e=>Qt(Ht(e,64)).reverse(),Gt=e=>BigInt("0x"+Kt(Tt(Ut(e)).reverse())),$t=(...e)=>{const t=Tt(e.reduce((e,t)=>e+Ut(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},jt=(e,t)=>{(0n===e||t<=0n)&&Rt("no inverse n="+e+" mod="+t);let r=Nt(e,t),s=t,i=0n,n=1n,o=1n,a=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-o*e,l=n-a*e;s=r,r=t,i=o,n=a,o=c,a=l}return 1n===s?Nt(i,t):Rt("no inverse")},qt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ct;return r},zt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Wt=(e,t)=>{const r=Nt(t*t*t),s=(e=>{const t=e*e%Ct*e%Ct,r=qt(t,2n)*t%Ct,s=qt(r,1n)*e%Ct,i=qt(s,5n)*s%Ct,n=qt(i,10n)*i%Ct,o=qt(n,20n)*n%Ct,a=qt(o,40n)*o%Ct,c=qt(a,80n)*a%Ct,l=qt(c,80n)*a%Ct,h=qt(l,10n)*i%Ct;return{pow_p_5_8:qt(h,2n)*e%Ct,b2:t}})(e*Nt(r*r*t)).pow_p_5_8;let i=Nt(e*r*s);const n=Nt(t*i*i),o=i,a=Nt(i*zt),c=n===e,l=n===Nt(-e),h=n===Nt(-e*zt);return c&&(i=o),(l||h)&&(i=a),1n==(1n&Nt(i))&&(i=Nt(-i)),{isValid:c||l,value:i}};let Jt;const Yt=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Zt={bytesToHex:Kt,hexToBytes:Qt,concatBytes:$t,mod:Nt,invert:jt,randomBytes:(e=32)=>{const t=Yt();return t&&t.getRandomValues||Rt("crypto.getRandomValues must be defined"),t.getRandomValues(Tt(e))},sha512Async:async(...e)=>{const t=Yt(),r=t&&t.subtle;r||Rt("etc.sha512Async or crypto.subtle must be defined");const s=$t(...e);return Tt(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let Xt;Object.defineProperties(Zt,{sha512Sync:{configurable:!1,get:()=>Jt,set(e){Jt||(Jt=e)}}});const er=e=>{const t=Xt||(Xt=(()=>{const e=[];let t=Pt,r=t;for(let s=0;s<33;s++){r=t,e.push(r);for(let s=1;s<128;s++)r=r.add(t),e.push(r);t=r.double()}return e})()),r=(e,t)=>{let r=t.negate();return e?r:t};let s=Lt,i=Pt;const n=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const c=128*a;let l=Number(e&n);e>>=o,l>128&&(l-=256,e+=1n);const h=c,u=c+Math.abs(l)-1,d=a%2!=0,g=l<0;0===l?i=i.add(r(d,t[h])):s=s.add(r(g,t[u]))}return{p:s,f:i}};var tr=o(625);const rr=32,sr=64;async function ir(e){if(0===e.length)return Promise.resolve([]);const t=e.reduce((e,{message:t,key:r,signature:s})=>e+r.length+s.length+t.length+1,0),r=new Uint8Array(t);let s=0;for(const{key:t,message:i,signature:n}of e){r.set(t.raw,s),s+=rr,r.set(n.raw,s),s+=sr;const e=i.length;y(e<256,`Message needs to be shorter than 256 bytes. Got: ${e}`),r[s]=e,s+=1,r.set(i.raw,s),s+=e}const i=Array.from((0,tr.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}U.blobFromString("jam_val_key_ed25519"),U.blobFromString("jam_val_key_bandersnatch");class nr extends w{anchor;bitfield;validatorIndex;signature;static Codec=we.Class(nr,{anchor:we.bytes(Re).asOpaque(),bitfield:mt(e=>we.bitVecFixLen(e.coresCount)),validatorIndex:we.u16.asOpaque(),signature:we.bytes(sr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new nr(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const or=mt(e=>bt(nr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),ar=e=>z.array((e=>z.object({anchor:Et.bytes32(),bitfield:z.fromString(t=>{const r=Math.ceil(e.coresCount/8);return G.fromBytes(U.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Et.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>nr.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class cr extends w{workReportHash;wasConsideredValid;key;signature;static Codec=we.Class(cr,{workReportHash:we.bytes(Re).asOpaque(),wasConsideredValid:we.bool,key:we.bytes(rr).asOpaque(),signature:we.bytes(sr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new cr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class lr extends w{workReportHash;key;signature;static Codec=we.Class(lr,{workReportHash:we.bytes(Re).asOpaque(),key:we.bytes(rr).asOpaque(),signature:we.bytes(sr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new lr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class hr extends w{isWorkReportValid;index;signature;static Codec=we.Class(hr,{isWorkReportValid:we.bool,index:we.u16.asOpaque(),signature:we.bytes(sr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new hr(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class ur extends w{workReportHash;votesEpoch;votes;static Codec=we.Class(ur,{workReportHash:we.bytes(Re).asOpaque(),votesEpoch:we.u32.asOpaque(),votes:mt(e=>Ie(we.sequenceFixLen(hr.Codec,e.validatorsSuperMajority)).convert(E,lt))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new ur(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class dr extends w{verdicts;culprits;faults;static Codec=we.Class(dr,{verdicts:we.sequenceVarLen(ur.Codec),culprits:we.sequenceVarLen(lr.Codec),faults:we.sequenceVarLen(cr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new dr(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const gr=e=>X(e),fr=e=>Y(e),pr=e=>X(e),yr=e=>te(e),mr=e=>Y(e),br=e=>X(e);function Ar(e,t){return y(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Ir=e=>mt(t=>bt(e,{fixedLength:t.validatorsCount}));function vr(e,t){return y(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const wr=e=>mt(t=>bt(e,{fixedLength:t.epochLength}));class Sr extends w{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=we.Class(Sr,{anchor:we.bytes(Re).asOpaque(),stateRoot:we.bytes(Re).asOpaque(),beefyRoot:we.bytes(Re).asOpaque(),lookupAnchor:we.bytes(Re).asOpaque(),lookupAnchorSlot:we.u32.asOpaque(),prerequisites:we.sequenceVarLen(we.bytes(Re).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Sr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n=[]){super(),this.anchor=e,this.stateRoot=t,this.beefyRoot=r,this.lookupAnchor=s,this.lookupAnchorSlot=i,this.prerequisites=n}}class Er extends w{treeRoot;index;static Codec=we.Class(Er,{treeRoot:we.bytes(Re),index:we.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Er(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Cr extends w{hash;len;static Codec=we.Class(Cr,{hash:we.bytes(Re).asOpaque(),len:we.u32});static create({hash:e,len:t}){return new Cr(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class kr extends w{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=we.Class(kr,{service:we.u32.asOpaque(),codeHash:we.bytes(Re).asOpaque(),payload:we.blob,refineGasLimit:we.u64.asOpaque(),accumulateGasLimit:we.u64.asOpaque(),importSegments:bt(Er.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:we.sequenceVarLen(Cr.Codec),exportCount:we.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:o,exportCount:a}){return new kr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=o,this.exportCount=a}}function xr(e){return m(e,e>=Br&&e<=_r,`WorkItemsCount: Expected '${Br} <= count <= ${_r}' got ${e}`)}const Br=1,_r=16;class Rr extends w{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=we.Class(Rr,{authorization:we.blob,authCodeHost:we.u32.asOpaque(),authCodeHash:we.bytes(Re).asOpaque(),parametrization:we.blob,context:Sr.Codec,items:we.sequenceVarLen(kr.Codec).convert(e=>e,e=>ht.new(e,xr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Rr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){super(),this.authorization=e,this.authCodeHost=t,this.authCodeHash=r,this.parametrization=s,this.context=i,this.items=n}}var Or,Ur;(Ur=Or||(Or={}))[Ur.ok=0]="ok",Ur[Ur.outOfGas=1]="outOfGas",Ur[Ur.panic=2]="panic",Ur[Ur.badCode=3]="badCode",Ur[Ur.codeOversize=4]="codeOversize";class Tr extends w{kind;okBlob;static Codec=we.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(X(t.kind)),t.kind===Or.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Or.ok){const r=e.bytesBlob();return new Tr(t,r)}if(t>Or.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Tr(t)},e=>{e.decoder.varU32()===Or.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Nr extends w{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=we.Class(Nr,{gasUsed:we.varU64.asOpaque(),importedSegments:we.varU32,extrinsicCount:we.varU32,extrinsicSize:we.varU32,exportedSegments:we.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Nr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.gasUsed=e,this.importedSegments=t,this.extrinsicCount=r,this.extrinsicSize=s,this.exportedSegments=i}}class Dr{serviceId;codeHash;payloadHash;gas;result;load;static Codec=we.Class(Dr,{serviceId:we.u32.asOpaque(),codeHash:we.bytes(Re).asOpaque(),payloadHash:we.bytes(Re),gas:we.u64.asOpaque(),result:Tr.Codec,load:Nr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new Dr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.serviceId=e,this.codeHash=t,this.payloadHash=r,this.gas=s,this.result=i,this.load=n}}class Mr extends w{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=we.Class(Mr,{hash:we.bytes(Re).asOpaque(),length:we.u32,erasureRoot:we.bytes(Re),exportsRoot:we.bytes(Re).asOpaque(),exportsCount:we.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new Mr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.hash=e,this.length=t,this.erasureRoot=r,this.exportsRoot=s,this.exportsCount=i}}class Pr extends w{workPackageHash;segmentTreeRoot;static Codec=we.Class(Pr,{workPackageHash:we.bytes(Re).asOpaque(),segmentTreeRoot:we.bytes(Re).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new Pr(e,t)}}class Lr extends w{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=we.Class(Lr,{workPackageSpec:Mr.Codec,context:Sr.Codec,coreIndex:p.isGreaterOrEqual(h.V0_6_5)?we.varU32.convert(e=>X(e),e=>{if(!Z(e))throw new Error(`Core index exceeds U16: ${e}`);return mr(e)}):we.u16.asOpaque(),authorizerHash:we.bytes(Re).asOpaque(),authorizationOutput:we.blob,segmentRootLookup:Ie(we.sequenceVarLen(Pr.Codec)),results:we.sequenceVarLen(Dr.Codec).convert(e=>e,e=>ht.new(e,xr(e.length))),authorizationGasUsed:we.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:o,authorizationGasUsed:a}){return new Lr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=o,this.authorizationGasUsed=a}}const Hr=[2,3];class Kr extends w{validatorIndex;signature;static Codec=we.Class(Kr,{validatorIndex:we.u16.asOpaque(),signature:we.bytes(sr).asOpaque()});static create({validatorIndex:e,signature:t}){return new Kr(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class Vr extends w{report;slot;credentials;static Codec=we.Class(Vr,{report:Lr.Codec,slot:we.u32.asOpaque(),credentials:bt(Kr.Codec,{minLength:Hr[0],maxLength:Hr[1],typicalLength:Hr[1]})});static create({report:e,slot:t,credentials:r}){return new Vr(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const Qr=mt(e=>bt(Vr.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class Fr extends w{bandersnatch;ed25519;static Codec=we.Class(Fr,{bandersnatch:we.bytes(xe).asOpaque(),ed25519:we.bytes(rr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new Fr(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class Gr extends w{entropy;ticketsEntropy;validators;static Codec=we.Class(Gr,{entropy:we.bytes(Re).asOpaque(),ticketsEntropy:we.bytes(Re).asOpaque(),validators:Ir(Fr.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new Gr(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const $r=e=>{const t=e.encoded().raw,r=t.length-96;return O.blobFrom(t.subarray(0,r))};class jr extends w{static Codec=we.Class(jr,{parentHeaderHash:we.bytes(Re).asOpaque(),priorStateRoot:we.bytes(Re).asOpaque(),extrinsicHash:we.bytes(Re).asOpaque(),timeSlotIndex:we.u32.asOpaque(),epochMarker:we.optional(Gr.Codec),ticketsMarker:we.optional(wr(wt.Codec)),offendersMarker:we.sequenceVarLen(we.bytes(rr).asOpaque()),bandersnatchBlockAuthorIndex:we.u16.asOpaque(),entropySource:we.bytes(96).asOpaque(),seal:we.bytes(96).asOpaque()});static create(e){return Object.assign(jr.empty(),e)}parentHeaderHash=U.zero(Re).asOpaque();priorStateRoot=U.zero(Re).asOpaque();extrinsicHash=U.zero(Re).asOpaque();timeSlotIndex=gr(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=fr(0);entropySource=U.zero(96).asOpaque();seal=U.zero(96).asOpaque();constructor(){super()}static empty(){return new jr}}class qr extends Oe{static Codec=we.Class(qr,{hash:we.bytes(Re).asOpaque(),data:jr.Codec.View});static create({hash:e,data:t}){return new Oe(e,t)}}const zr=qr.Codec;class Wr extends w{requester;blob;static Codec=we.Class(Wr,{requester:we.u32.asOpaque(),blob:we.blob});static create({requester:e,blob:t}){return new Wr(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const Jr=we.sequenceVarLen(Wr.Codec);class Yr extends w{tickets;preimages;guarantees;assurances;disputes;static Codec=we.Class(Yr,{tickets:St,preimages:Jr,guarantees:Qr,assurances:or,disputes:dr.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new Yr(e,t,i,r,s)}constructor(e,t,r,s,i){super(),this.tickets=e,this.preimages=t,this.guarantees=r,this.assurances=s,this.disputes=i}}class Zr extends w{header;extrinsic;static Codec=we.Class(Zr,{header:jr.Codec,extrinsic:Yr.Codec});static create({header:e,extrinsic:t}){return new Zr(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const Xr=z.object({target:Et.bytes32(),vote:"boolean",key:Et.bytes32(),signature:Et.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>cr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),es=z.object({target:Et.bytes32(),key:Et.bytes32(),signature:Et.ed25519Signature},({target:e,key:t,signature:r})=>lr.create({workReportHash:e,key:t,signature:r})),ts=z.object({vote:"boolean",index:"number",signature:Et.ed25519Signature},({vote:e,index:t,signature:r})=>hr.create({isWorkReportValid:e,index:t,signature:r})),rs=z.object({target:Et.bytes32(),age:"number",votes:z.array(ts)},({target:e,age:t,votes:r})=>ur.create({workReportHash:e,votesEpoch:t,votes:r})),ss=z.object({verdicts:z.array(rs),culprits:z.array(es),faults:z.array(Xr)},({verdicts:e,culprits:t,faults:r})=>dr.create({verdicts:e,culprits:t,faults:r})),is=z.object({anchor:Et.bytes32(),state_root:Et.bytes32(),beefy_root:Et.bytes32(),lookup_anchor:Et.bytes32(),lookup_anchor_slot:"number",prerequisites:z.array(Et.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Sr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),ns=z.object({ok:z.optional(z.fromString(O.parseBlob)),out_of_gas:z.optional(z.fromAny(()=>null)),panic:z.optional(z.fromAny(()=>null)),bad_code:z.optional(z.fromAny(()=>null)),code_oversize:z.optional(z.fromAny(()=>null))},e=>{const{ok:t,out_of_gas:r,panic:s,bad_code:i,code_oversize:n}=e;if(void 0!==t)return new Tr(X(Or.ok),t);if(null===r)return new Tr(X(Or.outOfGas));if(null===s)return new Tr(X(Or.panic));if(null===i)return new Tr(X(Or.badCode));if(null===n)return new Tr(X(Or.codeOversize));throw new Error("Invalid WorkExecResult")}),os=z.object({gas_used:z.fromNumber(e=>yr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Nr.create({gasUsed:yr(e),importedSegments:X(t),extrinsicCount:X(r),extrinsicSize:X(s),exportedSegments:X(i)})),as=z.object({service_id:"number",code_hash:Et.bytes32(),payload_hash:Et.bytes32(),accumulate_gas:z.fromNumber(e=>yr(e)),result:ns,refine_load:os},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>Dr.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),cs=z.object({hash:Et.bytes32(),length:"number",erasure_root:Et.bytes32(),exports_root:Et.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>Mr.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),ls=z.object({work_package_hash:Et.bytes32(),segment_tree_root:Et.bytes32()},({work_package_hash:e,segment_tree_root:t})=>Pr.create({workPackageHash:e,segmentTreeRoot:t})),hs=z.object({package_spec:cs,context:is,core_index:"number",authorizer_hash:Et.bytes32(),auth_output:z.fromString(O.parseBlob),segment_root_lookup:z.array(ls),results:z.array(as),auth_gas_used:z.fromNumber(e=>yr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:o,auth_gas_used:a})=>{const c=ht.new(n,xr(n.length));return Lr.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:o,results:c,authorizationGasUsed:a})}),us=z.object({validator_index:"number",signature:Et.ed25519Signature},({validator_index:e,signature:t})=>Kr.create({validatorIndex:e,signature:t})),ds=z.object({report:hs,slot:"number",signatures:z.array(us)},({report:e,slot:t,signatures:r})=>Vr.create({report:e,slot:t,credentials:r})),gs=z.array(ds),fs=z.object({requester:"number",blob:z.fromString(O.parseBlob)},({requester:e,blob:t})=>Wr.create({requester:e,blob:t})),ps=z.array(fs),ys=z.object({attempt:Et.ticketAttempt,signature:z.fromString(e=>U.parseBytes(e,784).asOpaque())},e=>vt.create({attempt:e.attempt,signature:e.signature})),ms=z.array(ys),bs=z.fromString(e=>U.parseBytes(e,96).asOpaque()),As=z.object({bandersnatch:Et.bytes32(),ed25519:Et.bytes32()},Fr.create),Is=z.object({entropy:Et.bytes32(),tickets_entropy:Et.bytes32(),validators:z.array(As)},e=>Gr.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),vs=z.object({id:Et.bytes32(),attempt:Et.ticketAttempt},e=>wt.create({id:e.id,attempt:e.attempt})),ws=z.object({parent:Et.bytes32(),parent_state_root:Et.bytes32(),extrinsic_hash:Et.bytes32(),slot:"number",epoch_mark:z.optional(Is),tickets_mark:z.optional(z.array(vs)),offenders_mark:z.array(Et.bytes32()),author_index:"number",entropy_source:bs,seal:bs},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:o,author_index:a,entropy_source:c,seal:l})=>{const h=jr.empty();return h.parentHeaderHash=e,h.priorStateRoot=t,h.extrinsicHash=r,h.timeSlotIndex=s,h.epochMarker=i??null,h.ticketsMarker=n??null,h.offendersMarker=o,h.bandersnatchBlockAuthorIndex=a,h.entropySource=c,h.seal=l,h});class Ss extends w{name;ip;port;static fromString(e){const[t,r]=e.split("@"),s=r.substring(0,r.lastIndexOf(":")),i=r.substring(r.lastIndexOf(":")+1);if(""===t||""===s||""===i)throw new Error(`Invalid bootnode format, expected: <name>@<ip>:<port>, got: "${e}"`);const n=Number.parseInt(i);if(!Z(n))throw new Error(`Invalid port number: "${i}"`);return new Ss(t,s,n)}constructor(e,t,r){super(),this.name=e,this.ip=t,this.port=r}}class Es extends w{bootnodes;id;genesisHeader;genesisState;static fromJson=z.object({bootnodes:z.optional(z.array(z.fromString(Ss.fromString))),id:"string",genesis_header:Et.bytesBlobNoPrefix,genesis_state:z.map(Et.bytesNNoPrefix(31),Et.bytesBlobNoPrefix)},e=>Es.create({bootnodes:e.bootnodes,id:e.id,genesisHeader:e.genesis_header,genesisState:e.genesis_state??new Map}));static create({bootnodes:e=[],id:t="",genesisHeader:r=O.empty(),genesisState:s=new Map}){return new Es({bootnodes:e,id:t,genesisHeader:r,genesisState:s})}constructor(e){super(),this.bootnodes=e.bootnodes,this.id=e.id,this.genesisHeader=e.genesisHeader,this.genesisState=e.genesisState}}const Cs=t(import.meta.url)("node:fs");var ks=o.n(Cs);const xs=t(import.meta.url)("node:os");var Bs=o.n(xs);const _s=JSON.parse('{"$schema":"./config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":false},"chain_spec":{"id":"typeberry-dev","bootnodes":["e3r2oc62zwfj3crnuifuvsxvbtlzetk4o5qyhetkhagsc2fgl2oka@127.0.0.1:40000","eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345","en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346","ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"],"genesis_header":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da293d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e948e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260fafff16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea020000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","genesis_state":{"01000000000000000000000000000000000000000000000000000000000000":"08000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","02000000000000000000000000000000000000000000000000000000000000":"0b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb0","03000000000000000000000000000000000000000000000000000000000000":"00","04000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf426000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000085f9095f4abd040839d793d89ab5ff25c61e50c844ab6765e2c0b22373b5a8f6fbe5fc0cd61fdde580b3d44fe1be127197e33b91960b10d2c6fc75aec03f36e16c2a8204961097dbc2c5ba7655543385399cc9ef08bf2e520ccf3b0a7569d88492e630ae2b14e758ab0960e372172203f4c9a41777dadd529971d7ab9d23ab29fe0e9c85ec450505dde7f5ac038274cf01aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d48e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e33d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d03d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d05e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161df16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d0aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bcaa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e300","05000000000000000000000000000000000000000000000000000000000000":"00000000","06000000000000000000000000000000000000000000000000000000000000":"6f6ad2224d7d58aec6573c623ab110700eaca20a48dc2965d535e466d524af2a835ac82bfa2ce8390bb50680d4b7a73dfa2a4cff6d8c30694b24a605f9574eafd2d34655ebcad804c56d2fd5f932c575b6a5dbb3f5652c5202bcc75ab9c2cc958a715731759b7fceaae288bcb70a605c31cbdfae83d0f4a45dfc2b2458dc9fae","07000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","08000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","09000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0a000000000000000000000000000000000000000000000000000000000000":"0000","0b000000000000000000000000000000000000000000000000000000000000":"00000000","0c000000000000000000000000000000000000000000000000000000000000":"00000000000000000000000000","0d000000000000000000000000000000000000000000000000000000000000":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0e000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","0f000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","ff000000000000000000000000000000000000000000000000000000000000":"15f8485e3a88e86182e63280720d5ec9892578f0e577fb1bcdda5cf49795081500e40b540200000064000000000000006400000000000000100500000000000004000000","00fe00ff00ff00ff6326432b5b3213dfd1609495e13c6b276cb474d6796453":"09626f6f74737472617000000000000000000020000a00000000000628023307320015","00fe00ff00ff00fff8485e3a88e86182e63280720d5ec9892578f0e577fb1b":"09626f6f747374726170000000000000020000200032040000050283ae7900300194012f027802280d00000028ae00000028ab029511e07b10187b15107b1608648664783309043307000001ac967c9566fc5106769587047d7833050159083a8489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac564564587b175010029c026478e45607c95707d88709e48707c98707887720d479098217c8750594983307000001da95072805330801821018821510821608951120320000951150ff7b10a8007b15a0007b169800330908ac98e7003309fcaa97e5015107e101958af8957508510a457d583306015908408489ff003306025329c0002d3306035329e000253306045329f0001d3306055329f800153306065329fc000d8898fe009a860801ae6a092890003306017b166457646864a6501004e501821a51077be4a607c9a70753176072c85a089576a09587607b1751064c7d783305015908378489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac562a016458501006810128073305330701e45608c95808e47808c97808330921ae981d33083307000001018210a8008215a000821698009511b00032008219c89505c857077c792051090933083307286e958adf957521510a547d573306015907378477ff003306025327c0002d3306035327e000253306045327f0001d3306055327f800153306065327fc000d8877fe009a7608017b1aac6a920064576468501008e6006478821a28073306330801c86507e46a09c96909e6890801c878088088fc330964330a640a0964757b1708481114951714330804951908330a040a0395171833098000330850100a4a330820a107330964951a1864570a0b81180833070000023b080000029889183b090300029889103b090200029888083b080100023308202806ff0000003307000001330832008d7a84aa07c8a70b510a0e647c0178c895cc01acbcfbc9a903843cf8c8cb0a580c1d8482ff0014090101010101010101ca920c017bbc95bb08acabfb843907520905280ec8a9090178a895aa01ac9afb320051089b0064797c77510791005127ff0090006c7a570a09330a330828735527c0000d330a01330b80284a5527e0000e330a02330b40ff283c5527f0000e330a03330b20ff282e5527f8000e330a04330b10ff28205527fc000e330a05330b08ff2812887afe00330b04ff93ab02ff85aa0701ae8a2b3308c8b70764ab01c8b90c7ccc97880895bbffd4c808520bf28aa903cf9707c88707320032000000002124492a21494a22212121212132154a9224a5909a248d88482422494924242424244426ad0a258924a524121212121222a3504d92a43022a292a44a52120909090909914585aa26c924a924494a1421a984909090903c54495a92241140962465495111942a24854421514814124544a6342549923a","0023000000000000478648cd19b4f812f897a26976ecf312eac28508b4368d":"0100000000","004b000400000000f324d112c31c3778a072940b55dd35f3a4b77e72d2d2db":"0100000000"}},"database_base_path":"./database"}');class Rs{omitSealVerification;static fromJson=z.object({omit_seal_verification:"boolean"},Rs.new);static new({omit_seal_verification:e}){return new Rs(e)}constructor(e){this.omitSealVerification=e}}const Os="dev",Us={name:Bs().hostname(),config:Os};var Ts;!function(e){e.Tiny="tiny",e.Full="full"}(Ts||(Ts={}));const Ns=z.fromString((e,t)=>{switch(e){case Ts.Tiny:return Ts.Tiny;case Ts.Full:return Ts.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class Ds{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=z.object({$schema:"string",version:"number",flavor:Ns,chain_spec:Es.fromJson,database_base_path:"string",authorship:Rs.fromJson},Ds.new);static new({$schema:e,version:t,flavor:r,chain_spec:s,database_base_path:i,authorship:n}){if(1!==t)throw new Error("Only version=1 config is supported.");return new Ds(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.$schema=e,this.version=t,this.flavor=r,this.chainSpec=s,this.databaseBasePath=i,this.authorship=n}}var Ms;function Ps(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===Ms[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return Ms[t]}!function(e){e[e.TRACE=1]="TRACE",e[e.LOG=2]="LOG",e[e.INFO=3]="INFO",e[e.WARN=4]="WARN",e[e.ERROR=5]="ERROR"}(Ms||(Ms={}));class Ls{options;static create(e,t){return e===Ms.TRACE?new Hs(t):e===Ms.LOG?new Ks(t):e===Ms.INFO?new Vs(t):new Ls(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(Ms.WARN,e,t,r)}error(e,t,r){this.push(Ms.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),o=function(e,t){let r=t;for(;;){const s=e.modules.get(r);if(void 0!==s)return s;const i=r.lastIndexOf("/");if(-1===i)return e.defaultLevel;r=t.substring(0,i)}}(this.options,t),a=Ms[e].padEnd(5);if(e<o)return;const c=`${a} [${n}] ${s}\n\t@ ${i}`;e===Ms.WARN?console.warn(c):e===Ms.ERROR?console.error(c):console.info(c)}}class Hs extends Ls{trace(e,t,r){this.push(Ms.TRACE,e,t,r)}log(e,t,r){this.push(Ms.LOG,e,t,r)}info(e,t,r){this.push(Ms.INFO,e,t,r)}}class Ks extends Ls{trace(e,t,r){}log(e,t,r){this.push(Ms.LOG,e,t,r)}info(e,t,r){this.push(Ms.INFO,e,t,r)}}class Vs extends Ls{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(Ms.INFO,e,t,r)}}const Qs={workingDir:"",defaultLevel:Ms.LOG,modules:new Map},Fs={options:Qs,transport:Ls.create(Qs.defaultLevel,Qs)};class Gs{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new Gs(t??r,r,Fs)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=Ls.create(t,e);Fs.options=e,Fs.transport=r}static configureAll(e,t,r){const s=function(e,t,r){const s=new Map,i=e.toLowerCase().split(",");let n=t;for(const e of i){const t=e.trim();if(0!==t.length)if(t.includes("=")){const[e,r]=t.split("=");s.set(e.trim(),Ps(r.trim()))}else n=Ps(t)}const o="".split("/");return o.pop(),o.pop(),{defaultLevel:n,modules:s,workingDir:r??o.join("/")}}(e,t,r);Gs.configureAllFromOptions(s)}constructor(e,t,r){this.moduleName=e,this.fileName=t,this.config=r}trace(e){this.config.transport.trace(this.moduleName,this.fileName,e)}log(e){this.config.transport.log(this.moduleName,this.fileName,e)}info(e){this.config.transport.info(this.moduleName,this.fileName,e)}warn(e){this.config.transport.warn(this.moduleName,this.fileName,e)}error(e){this.config.transport.error(this.moduleName,this.fileName,e)}}const $s=t(import.meta.url)("node:worker_threads"),js=e=>Ae.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=He(e.skipEncoded(r));return new Oe(s.asOpaque(),e.decode(t))},e.skip,e.View);class qs extends w{workReport;timeout;static Codec=we.Class(qs,{workReport:js(Lr.Codec),timeout:we.u32.asOpaque()});static create({workReport:e,timeout:t}){return new qs(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}class zs extends w{headerHash;mmr;postStateRoot;reported;static Codec=we.Class(zs,{headerHash:we.bytes(Re).asOpaque(),mmr:we.object({peaks:Ie(we.sequenceVarLen(we.optional(we.bytes(Re))))}),postStateRoot:we.bytes(Re).asOpaque(),reported:It(Pr.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new zs(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}function Ws(e,t){return y(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const Js=e=>mt(t=>bt(e,{fixedLength:t.coresCount})),Ys=()=>Ie(we.sequenceVarLen(we.bytes(Re))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return dt.fromSortedArray(ei,t)}),Zs=Ys();class Xs{goodSet;badSet;wonkySet;punishSet;static Codec=we.Class(Xs,{goodSet:Zs,badSet:Zs,wonkySet:Zs,punishSet:Ys()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new Xs(e,t,r,s)}constructor(e,t,r,s){this.goodSet=e,this.badSet=t,this.wonkySet=r,this.punishSet=s}static fromSortedArrays({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new Xs(dt.fromSortedArray(ei,e),dt.fromSortedArray(ei,t),dt.fromSortedArray(ei,r),dt.fromSortedArray(ei,s))}}function ei(e,t){return e.compare(t)}class ti{service;gasLimit;static Codec=we.Class(ti,{service:we.u32.asOpaque(),gasLimit:we.u64.asOpaque()});static create({service:e,gasLimit:t}){return new ti(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class ri{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=we.Class(ri,{manager:we.u32.asOpaque(),authManager:we.u32.asOpaque(),validatorsManager:we.u32.asOpaque(),autoAccumulateServices:Ie(we.sequenceVarLen(ti.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new ri(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const si=128;class ii extends w{bandersnatch;ed25519;bls;metadata;static Codec=we.Class(ii,{bandersnatch:we.bytes(xe).asOpaque(),ed25519:we.bytes(rr).asOpaque(),bls:we.bytes(_e).asOpaque(),metadata:we.bytes(si)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new ii(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var ni;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(ni||(ni={}));const oi=we.bytes(xe).asOpaque();class ai extends w{kind;keys;tickets;static Codec=mt(e=>we.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Re*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(X(t.kind)),t.kind===ni.Keys?e.sequenceFixLen(oi,t.keys):e.sequenceFixLen(wt.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===ni.Keys){const s=t.sequenceFixLen(oi,r);return ai.keys(vr(s,e))}if(s===ni.Tickets){const s=t.sequenceFixLen(wt.Codec,r);return ai.tickets(vr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==ni.Keys){if(r!==ni.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(wt.Codec,e.epochLength)}else t.sequenceFixLen(oi,e.epochLength)}));static keys(e){return new ai(ni.Keys,e,void 0)}static tickets(e){return new ai(ni.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class ci{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=we.Class(ci,{nextValidatorData:Ir(ii.Codec),epochRoot:we.bytes(Be).asOpaque(),sealingKeySeries:ai.Codec,ticketsAccumulator:Ie(we.sequenceVarLen(wt.Codec)).convert(E,lt)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new ci(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}class li extends w{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;storageUtilisationCount;static Codec=we.Class(li,{codeHash:we.bytes(Re).asOpaque(),balance:we.u64,accumulateMinGas:we.u64.convert(e=>e,yr),onTransferMinGas:we.u64.convert(e=>e,yr),storageUtilisationBytes:we.u64,storageUtilisationCount:we.u32});static create(e){return new li(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.storageUtilisationCount)}static calculateThresholdBalance(e,t){const r=se(te(100n),te(10n*BigInt(e)),te(1n*t));return r.overflow?te(2n**64n-1n):r.value}constructor(e,t,r,s,i,n){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.storageUtilisationCount=n}}class hi extends w{hash;blob;static Codec=we.Class(hi,{hash:we.bytes(Re).asOpaque(),blob:we.blob});static create({hash:e,blob:t}){return new hi(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class ui extends w{key;value;static Codec=we.Class(ui,{key:we.bytes(Re).asOpaque(),value:we.blob});static create({key:e,value:t}){return new ui(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function di(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class gi{hash;length;slots;constructor(e,t,r){this.hash=e,this.length=t,this.slots=r}static isRequested(e){return"slots"in e?0===e.slots.length:0===e.length}}var fi,pi,yi;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(fi||(fi={}));class mi{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new mi(e,{kind:fi.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new mi(e,{kind:fi.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new mi(e,{kind:fi.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case fi.Provide:return this.action.preimage.hash;case fi.Remove:return this.action.hash;case fi.UpdateOrAdd:return this.action.item.hash}throw b(this.action)}get length(){switch(this.action.kind){case fi.Provide:return X(this.action.preimage.blob.length);case fi.Remove:return this.action.length;case fi.UpdateOrAdd:return this.action.item.length}throw b(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(pi||(pi={}));class bi{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new bi(e,{kind:pi.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new bi(e,{kind:pi.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(yi||(yi={}));class Ai{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new Ai(e,{kind:yi.Set,storage:t})}static remove({serviceId:e,key:t}){return new Ai(e,{kind:yi.Remove,key:t})}get key(){return this.action.kind===yi.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===yi.Remove?null:this.action.storage.value}}const Ii=we.varU32.convert(e=>X(e),e=>pr(e));class vi{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=we.Class(vi,{blocks:we.u32,tickets:we.u32,preImages:we.u32,preImagesSize:we.u32,guarantees:we.u32,assurances:we.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new vi(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.blocks=e,this.tickets=t,this.preImages=r,this.preImagesSize=s,this.guarantees=i,this.assurances=n}static empty(){const e=X(0);return new vi(e,e,e,e,e,e)}}const wi=we.varU32.convert(e=>X(e),e=>Y(e)),Si=we.varU64.convert(e=>te(e),e=>yr(e));class Ei{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=we.Class(Ei,{dataAvailabilityLoad:we.varU32,popularity:wi,imports:wi,exports:wi,extrinsicSize:we.varU32,extrinsicCount:wi,bundleSize:we.varU32,gasUsed:Si});static create(e){return new Ei(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,o,a){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=o,this.gasUsed=a}static empty(){const e=X(0),t=Y(0),r=yr(0);return new Ei(e,t,t,t,e,t,e,r)}}class Ci{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=we.Class(Ci,{providedCount:wi,providedSize:we.varU32,refinementCount:we.varU32,refinementGasUsed:Si,imports:wi,exports:wi,extrinsicSize:we.varU32,extrinsicCount:wi,accumulateCount:we.varU32,accumulateGasUsed:Si,onTransfersCount:we.varU32,onTransfersGasUsed:Si});static create(e){return new Ci(e.providedCount,e.providedSize,e.refinementCount,e.refinementGasUsed,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.accumulateCount,e.accumulateGasUsed,e.onTransfersCount,e.onTransfersGasUsed)}constructor(e,t,r,s,i,n,o,a,c,l,h,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=o,this.extrinsicCount=a,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=h,this.onTransfersGasUsed=u}static empty(){const e=X(0),t=Y(0),r=yr(0);return new Ci(t,e,e,r,t,t,e,t,e,r,e,r)}}class ki{current;previous;cores;services;static Codec=we.Class(ki,{current:Ir(vi.Codec),previous:Ir(vi.Codec),cores:Js(Ei.Codec),services:we.dictionary(Ii,Ci.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new ki(e.current,e.previous,e.cores,e.services)}constructor(e,t,r,s){this.current=e,this.previous=t,this.cores=r,this.services=s}}var xi,Bi;(Bi=xi||(xi={}))[Bi.DuplicateService=0]="DuplicateService",Bi[Bi.NoService=1]="NoService",Bi[Bi.PreimageExists=2]="PreimageExists";class _i extends w{serviceId;data;constructor(e,t){super(),this.serviceId=e,this.data=t}getInfo(){return this.data.info}getStorage(e){return this.data.storage.get(e)?.value??null}hasPreimage(e){return this.data.preimages.has(e)}getPreimage(e){return this.data.preimages.get(e)?.blob??null}getLookupHistory(e,t){const r=this.data.lookupHistory.get(e);return void 0===r?null:r.find(e=>e.length===t)?.slots??null}getEntries(){return{storageKeys:Array.from(this.data.storage.keys()),preimages:Array.from(this.data.preimages.keys()),lookupHistory:Array.from(this.data.lookupHistory.entries()).map(([e,t])=>({hash:e,length:t[0].length}))}}static copyFrom(e,t){const r=e.getInfo(),s=at.new(),i=at.new(),n=at.new();for(const r of t.preimages){const t=e.getPreimage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected preimage: ${r}`);s.set(r,hi.create({hash:r,blob:t}))}for(const{hash:r,length:s}of t.lookupHistory){const t=e.getLookupHistory(r,s);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected lookupHistory: ${r}, ${s}`);const i=n.get(r)??[];i.push(new gi(r,s,t)),n.set(r,i)}for(const r of t.storageKeys){const t=e.getStorage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected storage: ${r}`);i.set(r,ui.create({key:r,value:t}))}return new _i(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class Ri extends w{static create(e){return new Ri(e)}static partial(e,t){const r=Ri.empty(e);return Object.assign(r,t),r}static copyFrom(e,t){const r=new Map;for(const[s,i]of t.entries()){const t=e.getService(s);if(null===t)throw new Error(`Expected service ${s} to be part of the state!`);const n=_i.copyFrom(t,i);r.set(s,n)}return Ri.create({availabilityAssignment:e.availabilityAssignment,accumulationQueue:e.accumulationQueue,designatedValidatorData:e.designatedValidatorData,nextValidatorData:e.nextValidatorData,currentValidatorData:e.currentValidatorData,previousValidatorData:e.previousValidatorData,disputesRecords:e.disputesRecords,timeslot:e.timeslot,entropy:e.entropy,authPools:e.authPools,authQueues:e.authQueues,recentBlocks:e.recentBlocks,statistics:e.statistics,recentlyAccumulated:e.recentlyAccumulated,ticketsAccumulator:e.ticketsAccumulator,sealingKeySeries:e.sealingKeySeries,epochRoot:e.epochRoot,privilegedServices:e.privilegedServices,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.keys()),preimages:Array.from(r.preimages.keys()),lookupHistory:Array.from(r.lookupHistory).flatMap(([e,t])=>t.map(t=>({hash:e,length:t.length})))});return e}applyUpdate(e){const{servicesRemoved:t,servicesUpdates:r,preimages:s,storage:i,...n}=e;let o;return Object.assign(this,n),o=this.updateServices(r),o.isError?o:(o=this.updatePreimages(s),o.isError?o:(o=this.updateStorage(i),o.isError?o:(this.removeServices(t),_.ok(C))))}removeServices(e){for(const t of e??[])y(this.services.has(t),`Attempting to remove non-existing service: ${t}`),this.services.delete(t)}updateStorage(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e}=r,s=this.services.get(t);if(void 0===s)return _.error(xi.NoService,`Attempting to update storage of non-existing service: ${t}`);e===yi.Set?s.data.storage.set(r.storage.key,r.storage):e===yi.Remove?(y(s.data.storage.has(r.key),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(r.key)):b(e)}return _.ok(C)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return _.error(xi.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===fi.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return _.error(xi.PreimageExists,`Overwriting existing preimage at ${t}: ${s}`);if(e.data.preimages.set(s.hash,s),null!==i){const t=e.data.lookupHistory.get(s.hash),r=X(s.blob.length),n=new gi(s.hash,r,di([i]));if(void 0===t)e.data.lookupHistory.set(s.hash,[n]);else{const e=t.map(e=>e.length).indexOf(r);t.splice(e,-1===e?0:1,n)}}}else if(s===fi.Remove){const{hash:t,length:s}=r;e.data.preimages.delete(t);const i=e.data.lookupHistory.get(t)??[],n=i.map(e=>e.length).indexOf(s);-1!==n&&i.splice(n,1)}else if(s===fi.UpdateOrAdd){const{item:t}=r,s=e.data.lookupHistory.get(t.hash)??[],i=s.map(e=>e.length).indexOf(t.length),n=-1===i?0:1;s.splice(i,n,t),e.data.lookupHistory.set(t.hash,s)}else b(s)}return _.ok(C)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===pi.Create){const{lookupHistory:e}=r;if(this.services.has(t))return _.error(xi.DuplicateService,`${t} already exists!`);this.services.set(t,new _i(t,{info:s,preimages:at.new(),storage:at.new(),lookupHistory:at.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===pi.Update){const e=this.services.get(t);if(void 0===e)return _.error(xi.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else b(e)}return _.ok(C)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;services;recentServiceIds(){return Array.from(this.services.keys())}getService(e){return this.services.get(e)??null}constructor(e){super(),this.availabilityAssignment=e.availabilityAssignment,this.designatedValidatorData=e.designatedValidatorData,this.nextValidatorData=e.nextValidatorData,this.currentValidatorData=e.currentValidatorData,this.previousValidatorData=e.previousValidatorData,this.disputesRecords=e.disputesRecords,this.timeslot=e.timeslot,this.entropy=e.entropy,this.authPools=e.authPools,this.authQueues=e.authQueues,this.recentBlocks=e.recentBlocks,this.statistics=e.statistics,this.accumulationQueue=e.accumulationQueue,this.recentlyAccumulated=e.recentlyAccumulated,this.ticketsAccumulator=e.ticketsAccumulator,this.sealingKeySeries=e.sealingKeySeries,this.epochRoot=e.epochRoot,this.privilegedServices=e.privilegedServices,this.services=e.services}static empty(e){return new Ri({availabilityAssignment:Ws(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Ar(Array.from({length:e.validatorsCount},()=>ii.create({bandersnatch:U.zero(xe).asOpaque(),bls:U.zero(_e).asOpaque(),ed25519:U.zero(rr).asOpaque(),metadata:U.zero(si).asOpaque()})),e),nextValidatorData:Ar(Array.from({length:e.validatorsCount},()=>ii.create({bandersnatch:U.zero(xe).asOpaque(),bls:U.zero(_e).asOpaque(),ed25519:U.zero(rr).asOpaque(),metadata:U.zero(si).asOpaque()})),e),currentValidatorData:Ar(Array.from({length:e.validatorsCount},()=>ii.create({bandersnatch:U.zero(xe).asOpaque(),bls:U.zero(_e).asOpaque(),ed25519:U.zero(rr).asOpaque(),metadata:U.zero(si).asOpaque()})),e),previousValidatorData:Ar(Array.from({length:e.validatorsCount},()=>ii.create({bandersnatch:U.zero(xe).asOpaque(),bls:U.zero(_e).asOpaque(),ed25519:U.zero(rr).asOpaque(),metadata:U.zero(si).asOpaque()})),e),disputesRecords:Xs.create({goodSet:dt.fromSortedArray(ei,[]),badSet:dt.fromSortedArray(ei,[]),wonkySet:dt.fromSortedArray(ei,[]),punishSet:dt.fromSortedArray(ei,[])}),timeslot:gr(0),entropy:ht.fill(()=>U.zero(Re).asOpaque(),4),authPools:Ws(Array.from({length:e.coresCount},()=>[]),e),authQueues:Ws(Array.from({length:e.coresCount},()=>ht.fill(()=>U.zero(Re).asOpaque(),80)),e),recentBlocks:[],statistics:ki.create({current:Ar(Array.from({length:e.validatorsCount},()=>vi.empty()),e),previous:Ar(Array.from({length:e.validatorsCount},()=>vi.empty()),e),cores:Ws(Array.from({length:e.coresCount},()=>Ei.empty()),e),services:new Map}),accumulationQueue:vr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:vr(Array.from({length:e.epochLength},()=>ct.new()),e),ticketsAccumulator:[],sealingKeySeries:ai.keys(vr(Array.from({length:e.epochLength},()=>U.zero(xe).asOpaque()),e)),epochRoot:U.zero(Be).asOpaque(),privilegedServices:ri.create({manager:pr(0),authManager:pr(0),validatorsManager:pr(0),autoAccumulateServices:[]}),services:new Map})}}const Oi=we.object({storageKeys:we.sequenceVarLen(we.bytes(Re).asOpaque()),preimages:we.sequenceVarLen(we.bytes(Re).asOpaque()),lookupHistory:we.sequenceVarLen(we.object({hash:we.bytes(Re).asOpaque(),length:we.u32}))});we.dictionary(we.u32.asOpaque(),Oi,{sortKeys:(e,t)=>e-t});class Ui extends w{report;dependencies;static Codec=we.Class(Ui,{report:Lr.Codec,dependencies:bt(we.bytes(Re).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new Ui(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var Ti,Ni,Di;!function(e){e[e.Unused=0]="Unused",e[e.Alpha=1]="Alpha",e[e.Phi=2]="Phi",e[e.Beta=3]="Beta",e[e.Gamma=4]="Gamma",e[e.Psi=5]="Psi",e[e.Eta=6]="Eta",e[e.Iota=7]="Iota",e[e.Kappa=8]="Kappa",e[e.Lambda=9]="Lambda",e[e.Rho=10]="Rho",e[e.Tau=11]="Tau",e[e.Chi=12]="Chi",e[e.Pi=13]="Pi",e[e.Theta=14]="Theta",e[e.Xi=15]="Xi",e[e.Delta=255]="Delta"}(Ti||(Ti={})),function(e){function t(e,t){const r=U.zero(Re);let s=0;for(const i of ie(e))r.raw[s]=i,r.raw[s+1]=t.raw[s/2],s+=2;const i=s/2;return r.raw.set(t.raw.subarray(i,Re-i),s),r.asOpaque()}e.index=function(e){const t=U.zero(Re);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=U.zero(Re);t.raw[0]=Ti.Delta;let r=1;for(const s of ie(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){const s=U.zero(Re);return s.raw.set(ie(X(2**32-1)),0),s.raw.set(r.raw.subarray(0,28),4),t(e,s)},e.servicePreimage=function(e,r){const s=U.zero(Re);return s.raw.set(ie(X(2**32-2)),0),s.raw.set(r.raw.subarray(1,29),4),t(e,s)},e.serviceLookupHistory=function(e,r,s){const i=He(r),n=U.zero(Re);return n.raw.set(ie(s),0),n.raw.set(i.raw.subarray(2,30),4),t(e,n)},e.serviceNested=t}(Ni||(Ni={})),function(e){e.authPools={key:Ni.index(Ti.Alpha),Codec:Js(bt(we.bytes(Re).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:Ni.index(Ti.Phi),Codec:Js(At(we.bytes(Re).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:Ni.index(Ti.Beta),Codec:bt(zs.Codec,{minLength:0,maxLength:8,typicalLength:8}),extract:e=>e.recentBlocks},e.safrole={key:Ni.index(Ti.Gamma),Codec:ci.Codec,extract:e=>ci.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:Ni.index(Ti.Psi),Codec:Xs.Codec,extract:e=>e.disputesRecords},e.entropy={key:Ni.index(Ti.Eta),Codec:At(we.bytes(Re).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:Ni.index(Ti.Iota),Codec:Ir(ii.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:Ni.index(Ti.Kappa),Codec:Ir(ii.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:Ni.index(Ti.Lambda),Codec:Ir(ii.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:Ni.index(Ti.Rho),Codec:Js(we.optional(qs.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:Ni.index(Ti.Tau),Codec:we.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:Ni.index(Ti.Chi),Codec:ri.Codec,extract:e=>e.privilegedServices},e.statistics={key:Ni.index(Ti.Pi),Codec:ki.Codec,extract:e=>e.statistics},e.accumulationQueue={key:Ni.index(Ti.Theta),Codec:wr(Ie(we.sequenceVarLen(Ui.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:Ni.index(Ti.Xi),Codec:wr(we.sequenceVarLen(we.bytes(Re).asOpaque()).convert(e=>Array.from(e),e=>ct.from(e))),extract:e=>e.recentlyAccumulated},e.serviceData=e=>({key:Ni.serviceInfo(e),Codec:li.Codec}),e.serviceStorage=(e,t)=>({key:Ni.serviceStorage(e,t),Codec:Mi}),e.servicePreimages=(e,t)=>({key:Ni.servicePreimage(e,t),Codec:Mi}),e.serviceLookupHistory=(e,t,r)=>({key:Ni.serviceLookupHistory(e,t,r),Codec:Ie(we.sequenceVarLen(we.u32))})}(Di||(Di={}));const Mi=Ae.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(U.fromBlob(t.raw,t.raw.length)),e=>O.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var Pi;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(Pi||(Pi={}));const Li=O.empty();class Hi{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new Hi(e,t,r)}static new(e,t,r=[]){return new Hi(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(Di.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new Ki(e,t,e=>this.retrieveOptional(e)))}retrieve({key:e,Codec:t},r){const s=this.backend.get(e);if(null===s)throw new Error(`Required state entry for ${r} is missing!. Accessing key: ${e}`);return ae.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return ae.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(Di.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(Di.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(Di.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(Di.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(Di.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(Di.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(Di.timeslot,"timeslot")}get entropy(){return this.retrieve(Di.entropy,"entropy")}get authPools(){return this.retrieve(Di.authPools,"authPools")}get authQueues(){return this.retrieve(Di.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(Di.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(Di.statistics,"statistics")}get accumulationQueue(){return this.retrieve(Di.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(Di.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(Di.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(Di.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(Di.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(Di.privilegedServices,"privilegedServices")}}class Ki{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){return this.retrieveOptional(Di.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(Di.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(Di.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(Di.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:di(r.map(gr))}}const Vi=31;var Qi;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(Qi||(Qi={}));class Fi{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?Qi.EmbedLeaf:Qi.Leaf:Qi.Branch}asBranchNode(){return y(this.getNodeType()===Qi.Branch),new Gi(this)}asLeafNode(){return y(this.getNodeType()!==Qi.Branch),new $i(this)}toString(){return O.blobFrom(this.raw).toString()}}class Gi{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new Fi;return r.raw.set(e.raw,0),r.raw.set(t.raw,Re),r.raw[0]&=127,new Gi(r)}getLeft(){return U.fromBlob(this.node.raw.subarray(0,Re),Re).asOpaque()}getRight(){return U.fromBlob(this.node.raw.subarray(Re),Re).asOpaque()}}class $i{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new Fi;return t.length<=Re?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,Vi),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,Vi),1),s.raw.set(r().raw,32)),new $i(s)}getKey(){return U.fromBlob(this.node.raw.subarray(1,32),Vi).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===Qi.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return O.blobFrom(this.node.raw.subarray(Re,Re+e))}getValueHash(){return U.fromBlob(this.node.raw.subarray(Re),Re).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}class ji{hasher;nodes=at.new();constructor(e){this.hasher=e}get(e){return ji.withHashCompat(e,e=>this.nodes.get(e)??null)}hashNode(e){return this.hasher.hashConcat(e.raw)}*leaves(){for(const e of this.nodes.values())e.getNodeType()!==Qi.Branch&&(yield e.asLeafNode())}static withHashCompat(e,t){const r=e.raw[0];e.raw[0]&=127;const s=t(e);return e.raw[0]=r,s}}class qi extends ji{remove(e){return ji.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return ji.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class zi{nodes;root;static empty(e){return new zi(new qi(e))}static computeStateRoot(e,t){return zi.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new qi(e);for(const e of t)r=Wi(r,s,e);return new zi(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=$i.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=Wi(this.root,this.nodes,s),s}remove(e){throw new Error("Removing from the trie not implemented yet.")}getRootNode(){return this.root}getRootHash(){return null===this.root?U.zero(Re).asOpaque():this.nodes.hashNode(this.root)}toString(){return Zi(this.root,this.nodes)}}function Wi(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new Ji;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==Qi.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),o=Yi(r,s.bitIndex),a=o?e.getRight():e.getLeft();s.branchingHistory.push([e,n,o]);const c=t.get(a);if(null===c){if(a.isEqualTo(U.zero(Re)))return s;throw new Error(`Missing trie node '${a}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=a,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,o]=r;const a=n.getKey(),c=t.insert(s.node);if(a.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(o),[s.node,c];const l=[];let h=Yi(i,e.bitIndex);for(;e.bitIndex<248;){h=Yi(i,e.bitIndex);const t=Yi(a,e.bitIndex);if(h!==t)break;l.push(t),e.bitIndex+=1}const u=U.zero(Re).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!h&&(o=t.hashNode(n.node));let d=h?Gi.fromSubNodes(o,c):Gi.fromSubNodes(c,o),g=t.insert(d.node),f=l.pop();for(;void 0!==f;)d=f?Gi.fromSubNodes(u,g):Gi.fromSubNodes(g,u),g=t.insert(d.node),f=l.pop();return[d.node,g]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[o,a]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?Gi.fromSubNodes(e.getLeft(),a):Gi.fromSubNodes(a,e.getRight());a=t.insert(c.node),o=c.node,n=s.branchingHistory.pop()}return o}class Ji{branchingHistory=[];bitIndex=0;leafToReplace}function Yi(e,t){y(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function Zi(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===Qi.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),o=Zi(t.get(s),t),a=Zi(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(o)}\n\t-- ${i}: ${n(a)}\n`}const r=e.asLeafNode(),s=r.getValueLength(),i=s>0?`'${r.getValue()}'(len:${s})`:`'<hash>${r.getValueHash()}'`;return`\nLeaf('${r.getKey().toString()}',${i})`}const Xi={hashConcat:(e,t=[])=>Le([e,...t])};class en{entries;static serializeInMemory(e,t){return new en({full:!0,data:tn(e,t)})}static fromDictionaryUnsafe(e){return new en({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new en({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}getTrie(){if(null===this.trieCache){const e=zi.empty(Xi);for(const[t,r]of this.entries.data)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}get(e){return this.entries.data.get(e)??null}applyUpdate(e){this.trieCache=null;for(const[t,r,s]of e)t===Pi.Insert?this.entries.data.set(r,s):t===Pi.Remove?this.entries.data.delete(r):b(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function tn(e,t){const r=at.new();function s(s){r.set(s.key,ge.encodeObject(s.Codec,s.extract(t),e))}s(Di.authPools),s(Di.authQueues),s(Di.recentBlocks),s(Di.safrole),s(Di.disputesRecords),s(Di.entropy),s(Di.designatedValidators),s(Di.currentValidators),s(Di.previousValidators),s(Di.availabilityAssignment),s(Di.timeslot),s(Di.privilegedServices),s(Di.statistics),s(Di.accumulationQueue),s(Di.recentlyAccumulated);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=Di.serviceData(e);r.set(t,ge.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=Di.servicePreimages(e,t.hash);r.set(s,ge.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=Di.serviceStorage(e,t.key);r.set(s,ge.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=Di.serviceLookupHistory(e,s.hash,s.length);r.set(t,ge.encodeObject(i,s.slots.slice()))}}return r}const rn=we.object({hash:we.bytes(Re).asOpaque(),length:we.u32,slots:Ie(we.sequenceVarLen(we.u32.asOpaque())).convert(E,di)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new gi(e,t,r)),sn=we.object({key:we.bytes(Re).asOpaque(),data:we.sequenceVarLen(rn)}),nn=we.sequenceVarLen(sn).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=at.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class on extends _i{static Codec=we.Class(on,{serviceId:we.u32.asOpaque(),data:we.object({info:li.Codec,preimages:It(hi.Codec,e=>e.hash),lookupHistory:nn,storage:It(ui.Codec,e=>e.key)})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new on(e,t)}}var an,cn,ln;we.Class(Ri,{authPools:Di.authPools.Codec,authQueues:Di.authQueues.Codec,recentBlocks:Di.recentBlocks.Codec,nextValidatorData:Ir(ii.Codec),epochRoot:we.bytes(Be).asOpaque(),sealingKeySeries:ai.Codec,ticketsAccumulator:Ie(we.sequenceVarLen(wt.Codec)).convert(e=>e,lt),disputesRecords:Di.disputesRecords.Codec,entropy:Di.entropy.Codec,designatedValidatorData:Di.designatedValidators.Codec,currentValidatorData:Di.currentValidators.Codec,previousValidatorData:Di.previousValidators.Codec,availabilityAssignment:Di.availabilityAssignment.Codec,timeslot:Di.timeslot.Codec,privilegedServices:Di.privilegedServices.Codec,statistics:Di.statistics.Codec,accumulationQueue:Di.accumulationQueue.Codec,recentlyAccumulated:Di.recentlyAccumulated.Codec,services:we.dictionary(we.u32.asOpaque(),on.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(an||(an={}));class hn{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=U.zero(Re).asOpaque();return r.raw.set(e.raw.subarray(0,Vi)),[r,t]});return new hn(at.fromEntries(t))}truncatedKey=U.zero(Re).asOpaque();constructor(e){this.dict=e}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Vi)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Vi)),this.dict.has(this.truncatedKey)}set(e,t){const r=U.zero(Re);r.raw.set(e.raw.subarray(0,Vi)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,Vi)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}!function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(cn||(cn={}));class un{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return _.error(cn.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new Fi(t.raw);if(e.getNodeType()===Qi.Branch)return _.error(cn.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return _.ok(new un(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=hn.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:ln.EmbeddedValue,value:e.getValue()}:{kind:ln.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===ln.EmbeddedValue?t.value:t.kind===ln.DbKey?O.blobFrom(this.db.get(t.key)):void b(t)}getStateRoot(){return zi.computeStateRoot(Xi,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(ln||(ln={}));const dn="best hash and posterior state root";class gn{chainSpec;root;extrinsics;headers;postStateRoots;constructor(e,t){this.chainSpec=e,this.root=t,this.extrinsics=this.root.subDb("extrinsics"),this.headers=this.root.subDb("headers"),this.postStateRoots=this.root.subDb("postStateRoots")}async setPostStateRoot(e,t){await this.postStateRoots.put(e.raw,t.raw)}getPostStateRoot(e){const t=this.postStateRoots.get(e.raw);return void 0===t?null:U.fromBlob(t,Re).asOpaque()}async insertBlock(e){const t=e.data.header.view().encoded(),r=e.data.extrinsic.view().encoded();await this.root.db.transaction(()=>{this.headers.put(e.hash.raw,t.raw),this.extrinsics.put(e.hash.raw,r.raw)})}async setBestHeaderHash(e){await this.root.db.put(dn,e.raw)}getBestHeaderHash(){const e=this.root.db.get(dn);return void 0===e?U.zero(Re).asOpaque():U.fromBlob(e,Re).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:ae.decodeObject(jr.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:ae.decodeObject(Yr.Codec.View,t,this.chainSpec)}}const fn=(pn={open:()=>r.open},yn={},o.d(yn,pn),yn);var pn,yn;class mn{db;constructor(e,t=!1){this.db=fn.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class bn{spec;root;states;values;constructor(e,t){this.spec=e,this.root=t,this.states=this.root.subDb("states"),this.values=this.root.subDb("values")}async insertState(e,t){const r=zi.empty(Xi);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[Pi.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===Pi.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===Pi.Remove?t.remove(i.asOpaque()):b(e);const i=O.blobFromParts(Array.from(t.nodes.leaves()).map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),o=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([o,n])}catch(e){return console.error(e),_.error(an.Commit)}return _.ok(C)}async updateAndSetState(e,t,r){const s=zi.fromLeaves(Xi,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[Pi.Insert,r.key,ge.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,Di.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,Di.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,Di.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return ci.create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s});if([e,t,r,s].some(e=>void 0!==e))throw new Error("SafroleData needs to be updated all at once!")}(t.nextValidatorData,t.epochRoot,t.sealingKeySeries,t.ticketsAccumulator);void 0!==s&&(yield r(s,Di.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,Di.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,Di.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,Di.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,Di.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,Di.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,Di.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,Di.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,Di.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,Di.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,Di.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,Di.recentlyAccumulated))}(e,t);const r=(t,r)=>ge.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=Di.serviceData(s);if(yield[Pi.Insert,e.key,t(e.Codec,r.account)],r.kind===pi.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=Di.serviceLookupHistory(s,e.hash,e.length);yield[Pi.Insert,i.key,t(i.Codec,e.slots)]}}}(t.servicesUpdates,r),yield*function*(e,t){for(const{action:r,serviceId:s}of e??[])switch(r.kind){case fi.Provide:{const{hash:e,blob:i}=r.preimage,n=Di.servicePreimages(s,e);if(yield[Pi.Insert,n.key,i],null!==r.slot){const n=Di.serviceLookupHistory(s,e,X(i.length));yield[Pi.Insert,n.key,t(n.Codec,di([r.slot]))]}break}case fi.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,o=Di.serviceLookupHistory(s,e,i);yield[Pi.Insert,o.key,t(o.Codec,n)];break}case fi.Remove:{const{hash:e,length:t}=r,i=Di.servicePreimages(s,e);yield[Pi.Remove,i.key,Li];const n=Di.serviceLookupHistory(s,e,t);yield[Pi.Remove,n.key,Li];break}default:b(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case yi.Set:{const e=Di.serviceStorage(r,t.storage.key);yield[Pi.Insert,e.key,t.storage.value];break}case yi.Remove:{const e=Di.serviceStorage(r,t.key);yield[Pi.Remove,e.key,Li];break}default:b(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=Di.serviceData(t);yield[Pi.Remove,e.key,Li]}}(t.servicesRemoved)}(this.spec,r);return await this.updateAndCommit(e,s,i)}async getStateRoot(e){return e.backend.getStateRoot()}getState(e){const t=this.states.get(e.raw);if(void 0===t)return null;const r=this.values,s=un.fromLeavesBlob(O.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${O.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${B(s)}`);return Hi.new(this.spec,s.ok)}}const An=t(import.meta.url)("node:events"),In=2**32,vn=Gs.new(void 0,"state-machine/port");class wn{port;listeners=new An.EventEmitter;responseListeners=new An.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw vn.error(`[${this.constructor.name}] Failed to dispatch a message: ${t}: ${JSON.stringify(e)}`),t}})}async sendRequest(e,t,r,s){const[i,n]=this.prepareRequest(e,t,r);return this.postMessage(i,s),n}sendSignal(e,t,r,s){this.messageId=(this.messageId+1)%In,this.messageId>>>=0,this.postMessage({kind:"signal",name:t,id:this.messageId,localState:e,data:r},s)}prepareRequest(e,t,r){this.messageId+=1;const s=new Promise((e,t)=>{this.responseListeners.once(Sn(this.messageId),(r,s)=>null!==r?t(r):e(s))});return[{kind:"request",id:this.messageId,name:t,localState:e,data:r},s]}respond(e,t,r){y("request"===t.kind),this.postMessage({kind:"response",id:t.id,name:t.name,data:r,localState:e})}close(){this.cleanup("closing"),this.listeners.removeAllListeners(),this.port.close()}postMessage(e,t){try{this.port.postMessage(e,t)}catch(t){throw vn.error(`[${this.constructor.name}] Failed to post a message: ${t}: ${JSON.stringify(e)}`),t}}dispatchPortMessage(e){if(!function(e){return null!==e&&"object"==typeof e&&"kind"in e&&"string"==typeof e.kind&&"id"in e&&"number"==typeof e.id&&"name"in e&&"string"==typeof e.name&&"data"in e&&"localState"in e&&"string"==typeof e.localState}(e))throw new Error(`Invalid message: ${JSON.stringify(e)}.`);switch(e.kind){case"response":y(-1!==this.responseListeners.eventNames().indexOf(Sn(e.id))),this.responseListeners.emit(Sn(e.id),null,e.data,e.name,e.localState,e);break;case"signal":this.listeners.emit("signal",e.name,e.data,e.localState,e);break;case"request":this.listeners.emit("request",e.name,e.data,e.localState,e);break;case"subscription":case"subscribe":throw new Error("unimplemented");default:throw new Error(`Unexpected message: "${e.kind}"`)}}cleanup(e){const t=this.responseListeners.eventNames();for(const r in t)this.responseListeners.emit(r,new Error(`port is ${e}`))}}function Sn(e){return`req:${e}`}const En=Gs.new(void 0,"state-machine"),Cn="channel";class kn{machine;port;constructor(e,t){this.machine=e,this.port=t,t.listeners.on("signal",(e,t,r)=>{try{this.dispatchSignal(e,t)}catch(t){throw En.error(`[${this.constructor.name}] Unable to dispatch signal (${e}): ${t}. ${this.stateInfo(r)}`),t}}),t.listeners.on("request",async(e,t,r,s)=>{try{await this.dispatchRequest(e,t,s)}catch(t){throw En.error(`[${this.constructor.name}] Unable to dispatch request (${e}): ${t}. ${this.stateInfo(r)}`),t}})}sendSignal(e,t){this.port.sendSignal(this.currentState().stateName,e,t)}async sendRequest(e,t){return this.port.sendRequest(this.currentState().stateName,e,t)}close(){this.port.close()}getState(e){return this.machine.getState(e)}currentState(){return this.machine.currentState()}async waitForState(e){return await this.machine.waitForState(e),this.transitionTo()}async doUntil(e,t){const r={isDone:!1},s=this.waitForState(e).then(()=>{r.isDone=!0});return await t(this.currentState(),this,()=>r.isDone),await s,this.transitionTo()}transition(e){const t=e(this.currentState(),this);return this.machine.transition(t.state,t.data),this.transitionTo()}stateInfo(e){return` (local state: "${this.currentState()}", remote state: "${e}")`}async dispatchRequest(e,t,r){const s=this.currentState(),i=s.requestHandlers.get(e);if(void 0===i)throw new Error(`Missing request handler for "${e}"`);const n=await i(t),o=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!o)return this.port.respond(s.stateName,r,n.response);En.warn(`Ignoring obsolete response for an old request: "${e}"`)}dispatchSignal(e,t){const r=this.currentState().signalListeners.get(e);if(void 0===r)throw new Error(`Unexpected signal "${e}"`);const s=r(t);void 0!==s&&this.machine.transition(s.state,s.data)}transitionTo(){return En.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new $s.MessageChannel,s=new wn(r.port2),i=e.currentState().stateName,[n,o]=s.prepareRequest(i,Cn,r.port1);t.postMessage(n,[r.port1]);try{await o}catch(e){En.error(JSON.stringify(e))}return new kn(e,s)}static async receiveChannel(e,t){if(null===t)throw new Error("This code is expected to be run in a worker.");const r=new Promise((r,s)=>{t.once("message",t=>{try{y("request"===t.kind,"The initial message should be a request with channel."),y(t.name===Cn),y(t.data instanceof $s.MessagePort);const s=new wn(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new kn(e,s)}}const xn=Symbol(),Bn=Symbol();class _n{emitter=new An.EventEmitter;emit(e){this.emitter.emit(xn,e)}on(e){return this.emitter.on(xn,e),this}once(e){return this.emitter.once(xn,e),this}onceDone(e){return this.emitter.once(Bn,e),this}markDone(){this.emitter.emit(Bn),this.emitter.removeAllListeners(xn),this.emitter.removeAllListeners(Bn)}}class Rn{name;state;allStates;stateListeners=new An.EventEmitter;constructor(e,t,r){this.name=e,this.state=t,this.allStates=new Map;for(const e of r)this.allStates.set(e.stateName,e)}getState(e){const t=this.allStates.get(e);return y(void 0!==t,`Unable to retrieve state object for ${e}.`),t}currentState(){return this.state}waitForState(e){if(this.state.stateName===e)throw new Error(`Attempting to await a state that is already active: ${e}`);return new Promise(t=>{this.stateListeners.once(e,t)})}transition(e,t){if(this.state.stateName===e)throw new Error("Attempting transition to already active state!");if(!this.state.canTransitionTo(e))throw new Error(`Unallowed transition from ${this.state} to ${e}`);const r=this.allStates.get(e);if(void 0===r)throw new Error(`Unavailable state: ${e}`);r.onActivation(t);const s=this.transitionTo(r);return s.stateListeners.emit(e,s),s}transitionTo(e){return this.state=e,this}}const On=Gs.new(void 0,"state-machine/state");class Un{stateName;signalListeners;requestHandlers;allowedTransitions;data=null;constructor({name:e,signalListeners:t={},requestHandlers:r={},allowedTransitions:s=[]}){this.stateName=e,this.allowedTransitions=s,this.signalListeners=new Map(Object.entries(t)),this.requestHandlers=new Map(Object.entries(r))}onActivation(e){On.trace(`[${this.constructor.name}] Changing state to: ${this}`),this.data=e}canTransitionTo(e){return-1!==this.allowedTransitions.indexOf(e)}toString(){return`<State ${this.stateName}>`}}class Tn extends Un{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class Nn extends Un{readyName;constructor(e){super({name:"init(main)",allowedTransitions:[e]}),this.readyName=e}sendConfig(e,t){return e.sendSignal("config",t),{state:this.readyName,data:t}}}class Dn extends Un{workerReadyName;handleConfig;constructor(e,t){super({name:"init(worker)",allowedTransitions:[e],signalListeners:{config:e=>this.onConfig(e)}}),this.workerReadyName=e,this.handleConfig=t}onConfig(e){return{state:this.workerReadyName,data:this.handleConfig(e)}}}async function Mn(e,t,r,s){const i=new $s.Worker(e),n=function(e,t,r){const s=new Nn(t),i=new Tn;return new Rn(e,s,[s,r,i])}(`main->${r}`,r,s),o=await kn.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${o.currentState()}`),o}const Pn=4294967295,Ln=4294967296,Hn=4096,Kn=(y(!0,"incorrect minimal allocation shift"),7),Vn=Hn>>Kn,Qn=1048575,Fn=1048576,Gn=e=>m(e,e>=0&&e<=Pn,`Incorrect memory index: ${e}!`),$n=e=>m(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var jn,qn;(qn=jn||(jn={}))[qn.OK=255]="OK",qn[qn.HALT=0]="HALT",qn[qn.PANIC=1]="PANIC",qn[qn.FAULT=2]="FAULT",qn[qn.HOST=3]="HOST",qn[qn.OOG=4]="OOG";const zn=e=>X(e);var Wn,Jn;!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(Wn||(Wn={}));class Yn{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return y(e>=0,`index (${e}) cannot be a negative number`),Math.min(this.lookupTableForward[e]??0,25)}buildLookupTableForward(e){const t=new Uint8Array(e.bitLength);let r=0;for(let s=e.bitLength-1;s>=0;s--)e.isSet(s)?r=0:r++,t[s]=r;return t}static empty(){return new Yn(G.empty(0))}}!function(e){e[e.NO_ARGUMENTS=0]="NO_ARGUMENTS",e[e.ONE_IMMEDIATE=1]="ONE_IMMEDIATE",e[e.TWO_IMMEDIATES=2]="TWO_IMMEDIATES",e[e.ONE_OFFSET=3]="ONE_OFFSET",e[e.ONE_REGISTER_ONE_IMMEDIATE=4]="ONE_REGISTER_ONE_IMMEDIATE",e[e.ONE_REGISTER_TWO_IMMEDIATES=5]="ONE_REGISTER_TWO_IMMEDIATES",e[e.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET=6]="ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET",e[e.TWO_REGISTERS=7]="TWO_REGISTERS",e[e.TWO_REGISTERS_ONE_IMMEDIATE=8]="TWO_REGISTERS_ONE_IMMEDIATE",e[e.TWO_REGISTERS_ONE_OFFSET=9]="TWO_REGISTERS_ONE_OFFSET",e[e.TWO_REGISTERS_TWO_IMMEDIATES=10]="TWO_REGISTERS_TWO_IMMEDIATES",e[e.THREE_REGISTERS=11]="THREE_REGISTERS",e[e.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE=12]="ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE"}(Jn||(Jn={}));class Zn{u32;i32;u64;i64;view;bytes;constructor(){const e=new ArrayBuffer(8);this.u32=new Uint32Array(e),this.i32=new Int32Array(e),this.u64=new BigUint64Array(e),this.i64=new BigInt64Array(e),this.view=new DataView(e),this.bytes=new Uint8Array(e)}setBytes(e){const t=e.length,r=t>0?128&e[t-1]:0,s=Math.min(t,8),i=0!==r?255:0;for(let t=0;t<s;t++)this.view.setUint8(t,e[t]);for(let e=t;e<8;e++)this.view.setUint8(e,i)}getUnsigned(){return this.u32[0]}getSigned(){return this.i32[0]}getU32(){return this.u32[0]}getI32(){return this.i32[0]}getU64(){return this.u64[0]}getI64(){return this.i64[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,4)}getExtendedBytesAsLittleEndian(){return this.bytes}}class Xn{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,y(104===e.length,"Invalid size of registers array."),this.asSigned=new BigInt64Array(e.buffer,e.byteOffset),this.asUnsigned=new BigUint64Array(e.buffer,e.byteOffset)}static fromBytes(e){return y(104===e.length,"Invalid size of registers array."),new Xn(e)}getBytesAsLittleEndian(e,t){const r=e<<3;return this.bytes.subarray(r,r+t)}getAllBytesAsLittleEndian(){return this.bytes}copyFrom(e){const t=e instanceof BigUint64Array?e:e.asUnsigned;this.asUnsigned.set(t)}reset(){for(let e=0;e<13;e++)this.asUnsigned[e]=0n}getLowerU32(e){return Number(0xffffffffn&this.asUnsigned[e])}getLowerI32(e){return 0|Number(this.getLowerU32(e))}setU32(e,t){this.asUnsigned[e]=eo(t)}setI32(e,t){this.asSigned[e]=eo(t)}getU64(e){return this.asUnsigned[e]}getI64(e){return this.asSigned[e]}setU64(e,t){this.asUnsigned[e]=t}setI64(e,t){this.asSigned[e]=t}getAllU64(){return this.asUnsigned}}function eo(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}class to{byte=new Int8Array(1);setByte(e){this.byte[0]=e}getHighNibble(){return(240&this.byte[0])>>>4}getLowNibble(){return 15&this.byte[0]}getHighNibbleAsRegisterIndex(){return Math.min(this.getHighNibble(),12)}getLowNibbleAsRegisterIndex(){return Math.min(this.getLowNibble(),12)}getHighNibbleAsLength(){return Math.min(this.getHighNibble(),4)}getLowNibbleAsLength(){return Math.min(this.getLowNibble(),4)}}class ro{nibblesDecoder=new to;offsetDecoder=new Zn;code=new Uint8Array;mask=Yn.empty();reset(e,t){this.code=e,this.mask=t}fillArgs(e,t){const r=1+this.mask.getNoOfBytesToNextInstruction(e+1);switch(t.noOfBytesToSkip=r,t.type){case Jn.NO_ARGUMENTS:break;case Jn.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case Jn.THREE_REGISTERS:{const r=this.code[e+1],s=this.code[e+2];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),this.nibblesDecoder.setByte(s),t.thirdRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Jn.TWO_REGISTERS_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));t.immediateDecoder.setBytes(this.code.subarray(i,n));break}case Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,o));const a=e+2+i,c=a+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(a,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Jn.TWO_REGISTERS_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));this.offsetDecoder.setBytes(this.code.subarray(i,n)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Jn.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Jn.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const o=this.offsetDecoder.getSigned();t.nextPc=e+o;break}case Jn.ONE_REGISTER_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2)),o=this.code.subarray(i,n);t.immediateDecoder.setBytes(o);break}case Jn.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case Jn.ONE_REGISTER_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case Jn.TWO_REGISTERS_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=this.code[e+2];this.nibblesDecoder.setByte(i);const n=this.nibblesDecoder.getLowNibbleAsLength(),o=e+3,a=o+n,c=this.code.subarray(o,a);t.firstImmediateDecoder.setBytes(c);const l=a,h=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,h);t.secondImmediateDecoder.setBytes(u);break}case Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const s=e+2,i=s+8,n=this.code.subarray(s,i);t.immediateDecoder.setBytes(n);break}}}}class so{unsignedImmediate;bytes;constructor(){const e=new ArrayBuffer(8);this.unsignedImmediate=new BigUint64Array(e),this.bytes=new Uint8Array(e)}setBytes(e){let t=0;for(;t<e.length;t++)this.bytes[t]=e[t];for(;t<8;t++)this.bytes[t]=0}getValue(){return this.unsignedImmediate[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,8)}}const io=Object.keys(Jn).length/2;var no;!function(e){e[e.TRAP=0]="TRAP",e[e.FALLTHROUGH=1]="FALLTHROUGH",e[e.ECALLI=10]="ECALLI",e[e.LOAD_IMM_64=20]="LOAD_IMM_64",e[e.STORE_IMM_U8=30]="STORE_IMM_U8",e[e.STORE_IMM_U16=31]="STORE_IMM_U16",e[e.STORE_IMM_U32=32]="STORE_IMM_U32",e[e.STORE_IMM_U64=33]="STORE_IMM_U64",e[e.JUMP=40]="JUMP",e[e.JUMP_IND=50]="JUMP_IND",e[e.LOAD_IMM=51]="LOAD_IMM",e[e.LOAD_U8=52]="LOAD_U8",e[e.LOAD_I8=53]="LOAD_I8",e[e.LOAD_U16=54]="LOAD_U16",e[e.LOAD_I16=55]="LOAD_I16",e[e.LOAD_U32=56]="LOAD_U32",e[e.LOAD_I32=57]="LOAD_I32",e[e.LOAD_U64=58]="LOAD_U64",e[e.STORE_U8=59]="STORE_U8",e[e.STORE_U16=60]="STORE_U16",e[e.STORE_U32=61]="STORE_U32",e[e.STORE_U64=62]="STORE_U64",e[e.STORE_IMM_IND_U8=70]="STORE_IMM_IND_U8",e[e.STORE_IMM_IND_U16=71]="STORE_IMM_IND_U16",e[e.STORE_IMM_IND_U32=72]="STORE_IMM_IND_U32",e[e.STORE_IMM_IND_U64=73]="STORE_IMM_IND_U64",e[e.LOAD_IMM_JUMP=80]="LOAD_IMM_JUMP",e[e.BRANCH_EQ_IMM=81]="BRANCH_EQ_IMM",e[e.BRANCH_NE_IMM=82]="BRANCH_NE_IMM",e[e.BRANCH_LT_U_IMM=83]="BRANCH_LT_U_IMM",e[e.BRANCH_LE_U_IMM=84]="BRANCH_LE_U_IMM",e[e.BRANCH_GE_U_IMM=85]="BRANCH_GE_U_IMM",e[e.BRANCH_GT_U_IMM=86]="BRANCH_GT_U_IMM",e[e.BRANCH_LT_S_IMM=87]="BRANCH_LT_S_IMM",e[e.BRANCH_LE_S_IMM=88]="BRANCH_LE_S_IMM",e[e.BRANCH_GE_S_IMM=89]="BRANCH_GE_S_IMM",e[e.BRANCH_GT_S_IMM=90]="BRANCH_GT_S_IMM",e[e.MOVE_REG=100]="MOVE_REG",e[e.SBRK=101]="SBRK",e[e.COUNT_SET_BITS_64=102]="COUNT_SET_BITS_64",e[e.COUNT_SET_BITS_32=103]="COUNT_SET_BITS_32",e[e.LEADING_ZERO_BITS_64=104]="LEADING_ZERO_BITS_64",e[e.LEADING_ZERO_BITS_32=105]="LEADING_ZERO_BITS_32",e[e.TRAILING_ZERO_BITS_64=106]="TRAILING_ZERO_BITS_64",e[e.TRAILING_ZERO_BITS_32=107]="TRAILING_ZERO_BITS_32",e[e.SIGN_EXTEND_8=108]="SIGN_EXTEND_8",e[e.SIGN_EXTEND_16=109]="SIGN_EXTEND_16",e[e.ZERO_EXTEND_16=110]="ZERO_EXTEND_16",e[e.REVERSE_BYTES=111]="REVERSE_BYTES",e[e.STORE_IND_U8=120]="STORE_IND_U8",e[e.STORE_IND_U16=121]="STORE_IND_U16",e[e.STORE_IND_U32=122]="STORE_IND_U32",e[e.STORE_IND_U64=123]="STORE_IND_U64",e[e.LOAD_IND_U8=124]="LOAD_IND_U8",e[e.LOAD_IND_I8=125]="LOAD_IND_I8",e[e.LOAD_IND_U16=126]="LOAD_IND_U16",e[e.LOAD_IND_I16=127]="LOAD_IND_I16",e[e.LOAD_IND_U32=128]="LOAD_IND_U32",e[e.LOAD_IND_I32=129]="LOAD_IND_I32",e[e.LOAD_IND_U64=130]="LOAD_IND_U64",e[e.ADD_IMM_32=131]="ADD_IMM_32",e[e.AND_IMM=132]="AND_IMM",e[e.XOR_IMM=133]="XOR_IMM",e[e.OR_IMM=134]="OR_IMM",e[e.MUL_IMM_32=135]="MUL_IMM_32",e[e.SET_LT_U_IMM=136]="SET_LT_U_IMM",e[e.SET_LT_S_IMM=137]="SET_LT_S_IMM",e[e.SHLO_L_IMM_32=138]="SHLO_L_IMM_32",e[e.SHLO_R_IMM_32=139]="SHLO_R_IMM_32",e[e.SHAR_R_IMM_32=140]="SHAR_R_IMM_32",e[e.NEG_ADD_IMM_32=141]="NEG_ADD_IMM_32",e[e.SET_GT_U_IMM=142]="SET_GT_U_IMM",e[e.SET_GT_S_IMM=143]="SET_GT_S_IMM",e[e.SHLO_L_IMM_ALT_32=144]="SHLO_L_IMM_ALT_32",e[e.SHLO_R_IMM_ALT_32=145]="SHLO_R_IMM_ALT_32",e[e.SHAR_R_IMM_ALT_32=146]="SHAR_R_IMM_ALT_32",e[e.CMOV_IZ_IMM=147]="CMOV_IZ_IMM",e[e.CMOV_NZ_IMM=148]="CMOV_NZ_IMM",e[e.ADD_IMM_64=149]="ADD_IMM_64",e[e.MUL_IMM_64=150]="MUL_IMM_64",e[e.SHLO_L_IMM_64=151]="SHLO_L_IMM_64",e[e.SHLO_R_IMM_64=152]="SHLO_R_IMM_64",e[e.SHAR_R_IMM_64=153]="SHAR_R_IMM_64",e[e.NEG_ADD_IMM_64=154]="NEG_ADD_IMM_64",e[e.SHLO_L_IMM_ALT_64=155]="SHLO_L_IMM_ALT_64",e[e.SHLO_R_IMM_ALT_64=156]="SHLO_R_IMM_ALT_64",e[e.SHAR_R_IMM_ALT_64=157]="SHAR_R_IMM_ALT_64",e[e.ROT_R_64_IMM=158]="ROT_R_64_IMM",e[e.ROT_R_64_IMM_ALT=159]="ROT_R_64_IMM_ALT",e[e.ROT_R_32_IMM=160]="ROT_R_32_IMM",e[e.ROT_R_32_IMM_ALT=161]="ROT_R_32_IMM_ALT",e[e.BRANCH_EQ=170]="BRANCH_EQ",e[e.BRANCH_NE=171]="BRANCH_NE",e[e.BRANCH_LT_U=172]="BRANCH_LT_U",e[e.BRANCH_LT_S=173]="BRANCH_LT_S",e[e.BRANCH_GE_U=174]="BRANCH_GE_U",e[e.BRANCH_GE_S=175]="BRANCH_GE_S",e[e.LOAD_IMM_JUMP_IND=180]="LOAD_IMM_JUMP_IND",e[e.ADD_32=190]="ADD_32",e[e.SUB_32=191]="SUB_32",e[e.MUL_32=192]="MUL_32",e[e.DIV_U_32=193]="DIV_U_32",e[e.DIV_S_32=194]="DIV_S_32",e[e.REM_U_32=195]="REM_U_32",e[e.REM_S_32=196]="REM_S_32",e[e.SHLO_L_32=197]="SHLO_L_32",e[e.SHLO_R_32=198]="SHLO_R_32",e[e.SHAR_R_32=199]="SHAR_R_32",e[e.ADD_64=200]="ADD_64",e[e.SUB_64=201]="SUB_64",e[e.MUL_64=202]="MUL_64",e[e.DIV_U_64=203]="DIV_U_64",e[e.DIV_S_64=204]="DIV_S_64",e[e.REM_U_64=205]="REM_U_64",e[e.REM_S_64=206]="REM_S_64",e[e.SHLO_L_64=207]="SHLO_L_64",e[e.SHLO_R_64=208]="SHLO_R_64",e[e.SHAR_R_64=209]="SHAR_R_64",e[e.AND=210]="AND",e[e.XOR=211]="XOR",e[e.OR=212]="OR",e[e.MUL_UPPER_S_S=213]="MUL_UPPER_S_S",e[e.MUL_UPPER_U_U=214]="MUL_UPPER_U_U",e[e.MUL_UPPER_S_U=215]="MUL_UPPER_S_U",e[e.SET_LT_U=216]="SET_LT_U",e[e.SET_LT_S=217]="SET_LT_S",e[e.CMOV_IZ=218]="CMOV_IZ",e[e.CMOV_NZ=219]="CMOV_NZ",e[e.ROT_L_64=220]="ROT_L_64",e[e.ROT_L_32=221]="ROT_L_32",e[e.ROT_R_64=222]="ROT_R_64",e[e.ROT_R_32=223]="ROT_R_32",e[e.AND_INV=224]="AND_INV",e[e.OR_INV=225]="OR_INV",e[e.XNOR=226]="XNOR",e[e.MAX=227]="MAX",e[e.MAX_U=228]="MAX_U",e[e.MIN=229]="MIN",e[e.MIN_U=230]="MIN_U"}(no||(no={}));const oo=no.MIN_U,ao=(()=>{const e=new Array(oo+1);return e[no.TRAP]=Jn.NO_ARGUMENTS,e[no.FALLTHROUGH]=Jn.NO_ARGUMENTS,e[no.ECALLI]=Jn.ONE_IMMEDIATE,e[no.LOAD_IMM_64]=Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[no.STORE_IMM_U8]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U16]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U32]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U64]=Jn.TWO_IMMEDIATES,e[no.JUMP]=Jn.ONE_OFFSET,e[no.JUMP_IND]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U64]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U64]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_IMM_IND_U8]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U16]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U32]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U64]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.LOAD_IMM_JUMP]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_EQ_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_NE_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LT_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LE_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GE_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GT_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LT_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LE_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GE_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GT_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.MOVE_REG]=Jn.TWO_REGISTERS,e[no.SBRK]=Jn.TWO_REGISTERS,e[no.COUNT_SET_BITS_64]=Jn.TWO_REGISTERS,e[no.COUNT_SET_BITS_32]=Jn.TWO_REGISTERS,e[no.LEADING_ZERO_BITS_64]=Jn.TWO_REGISTERS,e[no.LEADING_ZERO_BITS_32]=Jn.TWO_REGISTERS,e[no.TRAILING_ZERO_BITS_64]=Jn.TWO_REGISTERS,e[no.TRAILING_ZERO_BITS_32]=Jn.TWO_REGISTERS,e[no.SIGN_EXTEND_8]=Jn.TWO_REGISTERS,e[no.SIGN_EXTEND_16]=Jn.TWO_REGISTERS,e[no.ZERO_EXTEND_16]=Jn.TWO_REGISTERS,e[no.REVERSE_BYTES]=Jn.TWO_REGISTERS,e[no.STORE_IND_U8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ADD_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ADD_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.AND_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.XOR_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.OR_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.MUL_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.MUL_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_LT_U_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_LT_S_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.NEG_ADD_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.NEG_ADD_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_GT_U_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_GT_S_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.CMOV_IZ_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.CMOV_NZ_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_64_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_64_IMM_ALT]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_32_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_32_IMM_ALT]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.BRANCH_EQ]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_NE]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_LT_U]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_LT_S]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_GE_U]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_GE_S]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.LOAD_IMM_JUMP_IND]=Jn.TWO_REGISTERS_TWO_IMMEDIATES,e[no.ADD_32]=Jn.THREE_REGISTERS,e[no.ADD_64]=Jn.THREE_REGISTERS,e[no.SUB_32]=Jn.THREE_REGISTERS,e[no.SUB_64]=Jn.THREE_REGISTERS,e[no.AND]=Jn.THREE_REGISTERS,e[no.XOR]=Jn.THREE_REGISTERS,e[no.OR]=Jn.THREE_REGISTERS,e[no.MUL_32]=Jn.THREE_REGISTERS,e[no.MUL_64]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_S_S]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_U_U]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_S_U]=Jn.THREE_REGISTERS,e[no.DIV_U_32]=Jn.THREE_REGISTERS,e[no.DIV_S_32]=Jn.THREE_REGISTERS,e[no.REM_U_32]=Jn.THREE_REGISTERS,e[no.REM_S_32]=Jn.THREE_REGISTERS,e[no.DIV_U_64]=Jn.THREE_REGISTERS,e[no.DIV_S_64]=Jn.THREE_REGISTERS,e[no.REM_U_64]=Jn.THREE_REGISTERS,e[no.REM_S_64]=Jn.THREE_REGISTERS,e[no.SET_LT_U]=Jn.THREE_REGISTERS,e[no.SET_LT_S]=Jn.THREE_REGISTERS,e[no.SHLO_L_32]=Jn.THREE_REGISTERS,e[no.SHLO_R_32]=Jn.THREE_REGISTERS,e[no.SHAR_R_32]=Jn.THREE_REGISTERS,e[no.SHLO_L_64]=Jn.THREE_REGISTERS,e[no.SHLO_R_64]=Jn.THREE_REGISTERS,e[no.SHAR_R_64]=Jn.THREE_REGISTERS,e[no.CMOV_IZ]=Jn.THREE_REGISTERS,e[no.CMOV_NZ]=Jn.THREE_REGISTERS,e[no.ROT_L_64]=Jn.THREE_REGISTERS,e[no.ROT_L_32]=Jn.THREE_REGISTERS,e[no.ROT_R_64]=Jn.THREE_REGISTERS,e[no.ROT_R_32]=Jn.THREE_REGISTERS,e[no.AND_INV]=Jn.THREE_REGISTERS,e[no.OR_INV]=Jn.THREE_REGISTERS,e[no.XNOR]=Jn.THREE_REGISTERS,e[no.MAX]=Jn.THREE_REGISTERS,e[no.MAX_U]=Jn.THREE_REGISTERS,e[no.MIN]=Jn.THREE_REGISTERS,e[no.MIN_U]=Jn.THREE_REGISTERS,e})(),co=e=>X(e),lo=e=>te(e),ho=e=>"number"==typeof e&&e<2**32?co(e):lo(e);function uo(e){return new go(te(e))}class go{gas;constructor(e){this.gas=e}set(e){this.gas=te(e)}get(){return ho(this.gas)}sub(e){return this.gas=te(this.gas-te(e)),this.gas<0n}}const fo=[[no.TRAP,1],[no.FALLTHROUGH,1],[no.ECALLI,1],[no.LOAD_IMM_64,1],[no.STORE_IMM_U8,1],[no.STORE_IMM_U16,1],[no.STORE_IMM_U32,1],[no.STORE_IMM_U64,1],[no.JUMP,1],[no.JUMP_IND,1],[no.LOAD_IMM,1],[no.LOAD_U8,1],[no.LOAD_I8,1],[no.LOAD_U16,1],[no.LOAD_I16,1],[no.LOAD_U32,1],[no.LOAD_I32,1],[no.LOAD_U64,1],[no.STORE_U8,1],[no.STORE_U16,1],[no.STORE_U32,1],[no.STORE_U64,1],[no.STORE_IMM_IND_U8,1],[no.STORE_IMM_IND_U16,1],[no.STORE_IMM_IND_U32,1],[no.STORE_IMM_IND_U64,1],[no.LOAD_IMM_JUMP,1],[no.BRANCH_EQ_IMM,1],[no.BRANCH_NE_IMM,1],[no.BRANCH_LT_U_IMM,1],[no.BRANCH_LE_U_IMM,1],[no.BRANCH_GE_U_IMM,1],[no.BRANCH_GT_U_IMM,1],[no.BRANCH_LT_S_IMM,1],[no.BRANCH_LE_S_IMM,1],[no.BRANCH_GE_S_IMM,1],[no.BRANCH_GT_S_IMM,1],[no.MOVE_REG,1],[no.SBRK,1],[no.COUNT_SET_BITS_64,1],[no.COUNT_SET_BITS_32,1],[no.LEADING_ZERO_BITS_64,1],[no.LEADING_ZERO_BITS_32,1],[no.TRAILING_ZERO_BITS_64,1],[no.TRAILING_ZERO_BITS_32,1],[no.SIGN_EXTEND_8,1],[no.SIGN_EXTEND_16,1],[no.ZERO_EXTEND_16,1],[no.REVERSE_BYTES,1],[no.STORE_IND_U8,1],[no.STORE_IND_U16,1],[no.STORE_IND_U32,1],[no.STORE_IND_U64,1],[no.LOAD_IND_U8,1],[no.LOAD_IND_I8,1],[no.LOAD_IND_U16,1],[no.LOAD_IND_I16,1],[no.LOAD_IND_U32,1],[no.LOAD_IND_I32,1],[no.LOAD_IND_U64,1],[no.ADD_IMM_32,1],[no.AND_IMM,1],[no.XOR_IMM,1],[no.OR_IMM,1],[no.MUL_IMM_32,1],[no.SET_LT_U_IMM,1],[no.SET_LT_S_IMM,1],[no.SHLO_L_IMM_32,1],[no.SHLO_R_IMM_32,1],[no.SHAR_R_IMM_32,1],[no.NEG_ADD_IMM_32,1],[no.SET_GT_U_IMM,1],[no.SET_GT_S_IMM,1],[no.SHLO_L_IMM_ALT_32,1],[no.SHLO_R_IMM_ALT_32,1],[no.SHAR_R_IMM_ALT_32,1],[no.CMOV_IZ_IMM,1],[no.CMOV_NZ_IMM,1],[no.ADD_IMM_64,1],[no.MUL_IMM_64,1],[no.SHLO_L_IMM_64,1],[no.SHLO_R_IMM_64,1],[no.SHAR_R_IMM_64,1],[no.NEG_ADD_IMM_64,1],[no.SHLO_L_IMM_ALT_64,1],[no.SHLO_R_IMM_ALT_64,1],[no.SHAR_R_IMM_ALT_64,1],[no.ROT_R_64_IMM,1],[no.ROT_R_64_IMM_ALT,1],[no.ROT_R_32_IMM,1],[no.ROT_R_32_IMM_ALT,1],[no.BRANCH_EQ,1],[no.BRANCH_NE,1],[no.BRANCH_LT_U,1],[no.BRANCH_LT_S,1],[no.BRANCH_GE_U,1],[no.BRANCH_GE_S,1],[no.LOAD_IMM_JUMP_IND,1],[no.ADD_32,1],[no.SUB_32,1],[no.MUL_32,1],[no.DIV_U_32,1],[no.DIV_S_32,1],[no.REM_U_32,1],[no.REM_S_32,1],[no.SHLO_L_32,1],[no.SHLO_R_32,1],[no.SHAR_R_32,1],[no.ADD_64,1],[no.SUB_64,1],[no.MUL_64,1],[no.DIV_U_64,1],[no.DIV_S_64,1],[no.REM_U_64,1],[no.REM_S_64,1],[no.SHLO_L_64,1],[no.SHLO_R_64,1],[no.SHAR_R_64,1],[no.AND,1],[no.XOR,1],[no.OR,1],[no.MUL_UPPER_S_S,1],[no.MUL_UPPER_U_U,1],[no.MUL_UPPER_S_U,1],[no.SET_LT_U,1],[no.SET_LT_S,1],[no.CMOV_IZ,1],[no.CMOV_NZ,1],[no.ROT_L_64,1],[no.ROT_L_32,1],[no.ROT_R_64,1],[no.ROT_R_32,1],[no.AND_INV,1],[no.OR_INV,1],[no.XNOR,1],[no.MAX,1],[no.MAX_U,1],[no.MIN,1],[no.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:co(t)}])(t);return e[r]=s,e},{}),po=(()=>{const e=new Array(oo+1);return e.fill(!1),e[no.TRAP]=!0,e[no.FALLTHROUGH]=!0,e[no.JUMP]=!0,e[no.JUMP_IND]=!0,e[no.LOAD_IMM_JUMP]=!0,e[no.LOAD_IMM_JUMP_IND]=!0,e[no.BRANCH_EQ]=!0,e[no.BRANCH_NE]=!0,e[no.BRANCH_GE_U]=!0,e[no.BRANCH_GE_S]=!0,e[no.BRANCH_LT_U]=!0,e[no.BRANCH_LT_S]=!0,e[no.BRANCH_EQ_IMM]=!0,e[no.BRANCH_NE_IMM]=!0,e[no.BRANCH_LT_U_IMM]=!0,e[no.BRANCH_LT_S_IMM]=!0,e[no.BRANCH_LE_U_IMM]=!0,e[no.BRANCH_LE_S_IMM]=!0,e[no.BRANCH_GE_U_IMM]=!0,e[no.BRANCH_GE_S_IMM]=!0,e[no.BRANCH_GT_U_IMM]=!0,e[no.BRANCH_GT_S_IMM]=!0,e})();class yo{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&po[e[r]];for(let e=0;e<r;e++)t.isInstruction(e)&&s(e)&&this.basicBlocks.add(e+1+t.getNoOfBytesToNextInstruction(e+1))}isBeginningOfBasicBlock(e){return this.basicBlocks.has(e)}}const mo=(()=>{const e=new Array(oo+1);for(let t=0;t<oo+1;t++){const r=fo[t]?.gas;e[t]=r}return e})();class bo{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const Ao=e=>m(e,e>=0&&e<Hn,`Incorect page index: ${e}!`),Io=e=>m(e,e>=0&&e<=Qn,`Incorrect page number: ${e}!`);function vo(e){return Io(e===Qn?0:e+1)}function wo(e){return Hn*Math.ceil(e/Hn)}function So(e){return Io(e>>>12)}function Eo(e){return Gn(e>>>12<<12)}function Co(e){return Gn(e<<12>>>0)}class ko{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=Co(Io(e));return new ko(r,t)}static fromMemoryIndex(e,t=!1){const r=Eo(Gn(e%Ln));return new ko(r,t)}}class xo extends Error{constructor(){super("Out of bounds")}}Error,Error;class Bo extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class _o extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class Ro extends Error{constructor(){super("You are trying to access reserved memory!")}}class Oo extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class Uo extends Error{constructor(){super("Out of memory")}}class To{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Gn((this.start+this.length)%Ln),t>0&&(this.lastIndex=Gn((this.end-1+Ln)%Ln))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Ln)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new To(e,t)}isEmpty(){return 0===this.length}isWrapped(){return this.start>=this.end&&!this.isEmpty()}isInRange(e){return this.isWrapped()?e>=this.start||e<this.end:e>=this.start&&e<this.end}overlapsWith(e){return null!==this.lastIndex&&null!==e.lastIndex&&(this.isInRange(e.start)||this.isInRange(e.lastIndex)||e.isInRange(this.start)||e.isInRange(this.lastIndex))}}const No=To.fromStartAndLength(Gn(0),65536);class Do{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=Io((this.start+this.length)%Fn)}static fromMemoryRange(e){const t=So(e.start);if(e.isEmpty())return new Do(t,0);const r=So(e.lastIndex??e.end),s=vo(r);if((t===s||t===r)&&e.length>Hn)return new Do(t,Fn);const i=t<s?s-t:Fn-t+s;return Do.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Fn)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Do(e,t)}isEmpty(){return 0===this.length}*[Symbol.iterator](){if(this.isEmpty())return;const e=this.end;let t=this.start;do{yield t,t=vo(t)}while(t!==e)}}class Mo{start;constructor(e){this.start=Co(e)}}class Po extends Mo{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Hn)return _.error(ko.fromMemoryIndex(this.start+Hn));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),_.ok(C)}storeFrom(e,t){return _.error(ko.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Lo extends Mo{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Hn,Math.max(r,Vn));this.buffer=new ArrayBuffer(s,{maxByteLength:Hn}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Hn)return _.error(ko.fromMemoryIndex(this.start+Hn));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),_.ok(C)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Hn){const r=Math.min(Hn,Math.max(Vn,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),_.ok(C)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Hn){const r=Math.min(Hn,Math.max(Vn,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Ho;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Ho||(Ho={}));class Ko{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new Ko(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=$n(No.end),t=$n(No.end),r=$n(Pn),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=$n(No.end),this.virtualSbrkIndex=$n(No.end),this.endHeapIndex=$n(Pn),this.memory=new Map}copyFrom(e){this.sbrkIndex=e.sbrkIndex,this.virtualSbrkIndex=e.virtualSbrkIndex,this.endHeapIndex=e.endHeapIndex,this.memory=e.memory}storeFrom(e,t){if(0===t.length)return _.ok(C);const r=this.getPages(e,t.length,Ho.WRITE);if(r.isError)return _.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=Ao(i%Hn),o=Math.min(Hn-s,n),a=i-e,c=t.subarray(a,a+o);r.storeFrom(s,c),i+=o,n-=o}return _.ok(C)}getPages(e,t,r){if(0===t)return _.ok([]);const s=To.fromStartAndLength(e,t),i=Do.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return _.error(ko.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return _.error(ko.fromPageNumber(e));if(r===Ho.WRITE&&!t.isWriteable())return _.error(ko.fromPageNumber(e,!0));n.push(t)}return _.ok(n)}loadInto(e,t){if(0===e.length)return _.ok(C);const r=this.getPages(t,e.length,Ho.READ);if(r.isError)return _.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=Ao(i%Hn),o=Math.min(Hn-s,n),a=i-t,c=e.subarray(a);r.loadInto(c,s,o),i+=o,n-=o}return _.ok(C)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(Pn<r+e||r+e>this.endHeapIndex)throw new Uo;const s=$n(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=$n(wo(s)),n=So(t),o=(i-t)/Hn,a=Do.fromStartAndLength(n,o);for(const e of a){const t=new Lo(e);this.memory.set(e,t)}return this.virtualSbrkIndex=s,this.sbrkIndex=i,r}getPageDump(e){const t=this.memory.get(e);return t?.getPageDump()??null}getDirtyPages(){return this.memory.keys()}}class Vo{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new _o}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(No))throw new Ro}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),y(e<t,"end has to be bigger than start"),y(e%Hn===0,"start needs to be a multiple of page size (4096)"),y(t%Hn===0,"end needs to be a multiple of page size (4096)"),y(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Do.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Hn,(e+1)*Hn),i=new Po(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),y(e<t,"end has to be bigger than start"),y(e%Hn===0,"start needs to be a multiple of page size (4096)"),y(t%Hn===0,"end needs to be a multiple of page size (4096)"),y(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Do.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Hn,(e+1)*Hn),i=new Lo(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Hn-e%Hn;y(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=So(e),o=this.initialMemory.get(n);if(void 0===o)throw new Oo;const a=Ao(e-o.start);return o.setData(a,t),this}finalize(e,t){y(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=To.fromStartAndLength(e,t-e),s=Do.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new Bo;const i=Ko.fromInitialMemory({memory:this.initialMemory,sbrkIndex:$n(e),endHeapIndex:t});return this.isFinalized=!0,i}}class Qo{mathOps;shiftOps;bitOps;booleanOps;moveOps;bitRotationOps;constructor(e,t,r,s,i,n){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.bitRotationOps=n}dispatch(e,t){switch(e){case no.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class Fo{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,o,a){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=o,this.bitRotationOps=a}dispatch(e,t){switch(e){case no.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class Go{moveOps;memoryOps;bitOps;bitRotationOps;constructor(e,t,r,s){this.moveOps=e,this.memoryOps=t,this.bitOps=r,this.bitRotationOps=s}dispatch(e,t){switch(e){case no.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class $o{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case no.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case no.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class jo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case no.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class qo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===no.JUMP&&this.branchOps.jump(t.nextPc)}}class zo{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case no.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case no.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class Wo{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case no.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class Jo{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case no.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class Yo{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case no.TRAP:this.noArgsOps.trap();break;case no.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class Zo{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case no.LOAD_IMM_JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.secondImmediateDecoder,t.secondRegisterIndex);this.loadOps.loadImmediate(t.firstRegisterIndex,t.firstImmediateDecoder),this.dynamicJumpOps.jumpInd(e);break}}}}class Xo{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===no.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class ea{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===no.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class ta{regs;constructor(e){this.regs=e}or(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|this.regs.getU64(t))}orImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|t.getU64())}and(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&this.regs.getU64(t))}andImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&t.getU64())}xor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^this.regs.getU64(t))}xorImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^t.getU64())}andInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&~this.regs.getU64(t))}orInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|~this.regs.getU64(t))}xnor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^~this.regs.getU64(t))}countSetBits64(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1n&0x5555555555555555n,t=(0x3333333333333333n&t)+(t>>2n&0x3333333333333333n),t=t+(t>>4n)&0x0f0f0f0f0f0f0f0fn,t+=t>>8n,t+=t>>16n,t+=t>>32n,Number(0x7fn&t)}(this.regs.getU64(e)))}countSetBits32(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,63&t}(this.regs.getLowerU32(e)))}leadingZeroBits64(e,t){this.regs.setU32(t,function(e){const t=Number(e>>32n),r=Number(0xffffffffn&e),s=Math.clz32(t);return s<32?s:s+Math.clz32(r)}(this.regs.getU64(e)))}leadingZeroBits32(e,t){this.regs.setU32(t,Math.clz32(this.regs.getLowerU32(e)))}trailingZeroBits64(e,t){this.regs.setU32(t,function(e){if(0n===e)return 64;let t=e,r=0;for(;0n==(1n&t);)r++,t>>=1n;return r}(this.regs.getU64(e)))}trailingZeroBits32(e,t){this.regs.setU32(t,function(e){if(0===e)return 32;let t=e,r=0;for(;!(1&t);)r++,t>>>=1;return r}(this.regs.getLowerU32(e)))}signExtend(e,t){const r=2**t-1,s=e&r;return(s&1<<t-1)>0?~BigInt(r)|BigInt(s):BigInt(s)}signExtend8(e,t){const r=this.signExtend(this.regs.getLowerU32(e),8);this.regs.setU64(t,r)}signExtend16(e,t){const r=this.signExtend(this.regs.getLowerU32(e),16);this.regs.setU64(t,r)}zeroExtend16(e,t){const r=0x000000000000ffffn&this.regs.getU64(e);this.regs.setU64(t,r)}}const ra=4294967295,sa=-(2**31),ia=32,na=64n;function oa(e,t){return e>ra-t?ra-(ra-e+(ra-t))-1:e+t}function aa(e,t){return(e+t)%2n**64n}function ca(e,t){return t>e?ra-t+e+1:e-t}function la(e,t){return(2n**64n+e-t)%2n**64n}function ha(e,t){if(e>65536||t>65536){const r=65535&e,s=65535&t,i=r*s;return 65535&i|(i>>16)+(65535&r*(t>>16))+(65535&(e>>16)*s)<<16}return e*t}function ua(e,t){return e*t%2n**64n}function da(e){return e>=1n<<63n?e-(1n<<64n):e}function ga(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function fa(e,t){return da(0xffffffffffffffffn&e*t>>64n)}function pa(e,t){y(t>=0,"Shift count must be non-negative");const r=e<0?"1":"0",s=e.toString(2).padStart(64,r);return(e<0n?(1n<<BigInt(s.length))+e:e)>>t}function ya(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function ma(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class ba{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%ia)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%na)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%ia)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,pa(this.regs.getU64(e),this.regs.getU64(t)%na))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%ia)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%na)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%ia)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%na)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%ia)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,pa(this.regs.getU64(e),t.getU64()%na))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%ia)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%na)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%ia)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%na)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%ia)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,pa(t.getU64(),this.regs.getU64(e)%na))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%ia)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%na)}}class Aa{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,eo(oa(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,aa(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,eo(oa(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,aa(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,eo(ha(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,ua(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,ga(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,fa(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,da(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,eo(ha(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,ua(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,fa(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,ga(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,eo(ca(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,la(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,eo(ca(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,la(t.getU64(),this.regs.getU64(e)))}divSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===sa?this.regs.setU64(r,eo(this.regs.getLowerU32(e))):this.regs.setI64(r,eo(~~(this.regs.getLowerI32(e)/this.regs.getLowerI32(t))))}divSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setI64(r,~~(this.regs.getI64(e)/this.regs.getI64(t)))}divUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,eo(~~(this.regs.getLowerU32(e)/this.regs.getLowerU32(t))))}divUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,~~(this.regs.getU64(e)/this.regs.getU64(t)))}remSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,BigInt(this.regs.getLowerI32(e))):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===sa?this.regs.setU64(r,0n):this.regs.setI64(r,eo(this.regs.getLowerI32(e)%this.regs.getLowerI32(t)))}remSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,0n):this.regs.setI64(r,this.regs.getI64(e)%this.regs.getI64(t))}remUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,eo(this.regs.getLowerU32(e))):this.regs.setU64(r,eo(this.regs.getLowerU32(e)%this.regs.getLowerU32(t)))}remUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setU64(r,this.regs.getU64(e)%this.regs.getU64(t))}max(e,t,r){this.regs.setI64(r,ya(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,ma(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,ma(this.regs.getU64(e),this.regs.getU64(t)))}}class Ia{regs;constructor(e){this.regs=e}setLessThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<t.getI64()?1n:0n)}setLessThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<t.getU64()?1n:0n)}setLessThanSigned(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<this.regs.getI64(t)?1n:0n)}setLessThanUnsigned(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<this.regs.getU64(t)?1n:0n)}setGreaterThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>t.getI64()?1n:0n)}setGreaterThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)>t.getU64()?1n:0n)}}class va{regs;constructor(e){this.regs=e}cmovIfZeroImmediate(e,t,r){0n===this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfNotZeroImmediate(e,t,r){0n!==this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfZero(e,t,r){0n===this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}cmovIfNotZero(e,t,r){0n!==this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}moveRegister(e,t){this.regs.setU64(t,this.regs.getU64(e))}}var wa,Sa;(Sa=wa||(wa={}))[Sa.HALT=0]="HALT",Sa[Sa.PANIC=1]="PANIC",Sa[Sa.FAULT_ACCESS=2]="FAULT_ACCESS",Sa[Sa.FAULT=3]="FAULT",Sa[Sa.HOST=4]="HOST";class Ea{regs;instructionResult;basicBlocks;constructor(e,t,r){this.regs=e,this.instructionResult=t,this.basicBlocks=r}setBasicBlocks(e){this.basicBlocks=e}branch(e,t){t&&(this.basicBlocks.isBeginningOfBasicBlock(e)?this.instructionResult.nextPc=e:this.instructionResult.status=wa.PANIC)}jump(e){this.branch(e,!0)}branchEqImmediate(e,t,r){this.branch(r,this.regs.getU64(e)===t.getU64())}branchEq(e,t,r){this.branch(r,this.regs.getU64(e)===this.regs.getU64(t))}branchNeImmediate(e,t,r){this.branch(r,this.regs.getU64(e)!==t.getU64())}branchNe(e,t,r){this.branch(r,this.regs.getU64(e)!==this.regs.getU64(t))}branchLtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<t.getU64())}branchLtUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)<this.regs.getU64(t))}branchLeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<=t.getU64())}branchGtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>t.getU64())}branchGeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>=t.getU64())}branchGeUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)>=this.regs.getU64(t))}branchLtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<t.getI64())}branchLtSigned(e,t,r){this.branch(r,this.regs.getI64(e)<this.regs.getI64(t))}branchLeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<=t.getI64())}branchGtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>t.getI64())}branchGeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>=t.getI64())}branchGeSigned(e,t,r){this.branch(r,this.regs.getI64(e)>=this.regs.getI64(t))}}class Ca{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}loadImmediate(e,t){this.regs.setU64(e,t.getU64())}loadImmediateU64(e,t){this.regs.setU64(e,t.getValue())}loadNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Gn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=e):s.fill(0,r)}loadSignedNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Gn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=e):(128&s[r-1])>0?s.fill(255,r):s.fill(0,r)}loadU8(e,t){this.loadNumber(e,t,1)}loadU16(e,t){this.loadNumber(e,t,2)}loadU32(e,t){this.loadNumber(e,t,4)}loadU64(e,t){this.loadNumber(e,t,8)}loadI8(e,t){this.loadSignedNumber(e,t,1)}loadI16(e,t){this.loadSignedNumber(e,t,2)}loadI32(e,t){this.loadSignedNumber(e,t,4)}loadIndU8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class ka{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}storeU8(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,1))}storeU16(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,2))}storeU32(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,4))}storeU64(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,8))}storeIndU8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,8))}storeImmediateU8(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,1))}storeImmediateU16(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,2))}storeImmediateU32(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,4))}storeImmediateU64(e,t){this.store(e,t.getExtendedBytesAsLittleEndian())}storeImmediateIndU8(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Gn(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=Eo(r.error.address)))}}class xa{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=wa.PANIC}fallthrough(){}}class Ba{regs;jumpTable;instructionResult;basicBlocks;constructor(e,t,r,s){this.regs=e,this.jumpTable=t,this.instructionResult=r,this.basicBlocks=s}djump(e){if(4294901760===e)return void(this.instructionResult.status=wa.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=wa.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=wa.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=wa.PANIC}caluclateJumpAddress(e,t){return oa(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class _a{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=wa.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class Ra{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}sbrk(e,t){try{this.regs.setU32(t,this.memory.sbrk(this.regs.getLowerU32(e)))}catch{this.instructionResult.status=wa.FAULT}}}class Oa{regs;constructor(e){this.regs=e}reverseBytes(e,t){const r=this.regs.getU64(e);let s=0n;for(let e=0;e<8;e++)s=s<<8n|r>>BigInt(8*e)&0xffn;this.regs.setU64(t,s)}rotate32Left(e,t){const r=t%32,s=2**32-1;return(e<<r&s|e>>>32-r)>>>0&s}rotate64Left(e,t){const r=t%64,s=(1n<<64n)-1n;return(e<<BigInt(r)&s|pa(e,BigInt(64-r)))&s}rotate32Right(e,t){const r=t%32,s=2**32-1;return(e>>>r|e<<32-r&s)&s}rotate64Right(e,t){const r=t%64,s=(1n<<64n)-1n;return(pa(e,BigInt(r))|e<<BigInt(64-r)&s)&s}rotR64Imm(e,t,r){const s=t.getU32(),i=this.regs.getU64(e);this.regs.setU64(r,this.rotate64Right(i,s))}rotR64ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU64();this.regs.setU64(r,this.rotate64Right(i,s))}rotR32Imm(e,t,r){const s=t.getU32(),i=this.regs.getLowerU32(e);this.regs.setU32(r,this.rotate32Right(i,s))}rotR32ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU32();this.regs.setU32(r,this.rotate32Right(i,s))}rotL64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Left(s,i))}rotL32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Left(s,i))}rotR64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Right(s,i))}rotR32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Right(s,i))}}class Ua{indices;constructor(e,t){y(0===e||t.length%e===0,`Length of jump table (${t.length}) should be a multiple of item lenght (${e})!`);const r=0===e?0:t.length/e;this.indices=new Uint32Array(r);for(let s=0;s<r;s++)this.indices[s]=this.decodeNext(t.subarray(s*e,(s+1)*e))}decodeNext(e){const t=e.length;let r=0;for(let s=0;s<t;s++){if((4278190080&r)>0)return 2**32-1;r<<=8,r|=e[t-s-1]}return r}hasIndex(e){return e<this.indices.length&&e>=0}getDestination(e){return this.indices[e]}static empty(){return new Ua(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const Ta=Gs.new(void 0,"pvm-interpreter");var Na;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(Na||(Na={}));class Da{code;mask;jumpTable;constructor(e){const{code:t,mask:r,jumpTable:s,jumpTableItemLength:i}=this.decodeProgram(e);this.code=new Uint8Array(t),this.mask=new Yn(r),this.jumpTable=new Ua(i,s)}decodeProgram(e){const t=ae.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,o=t.bytes(n).raw,a=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:a,jumpTableItemLength:s,jumpTable:o}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return _.ok(new Da(e))}catch(e){return Ta.error(`Invalid program: ${e}`),_.error(Na.InvalidProgramError)}}}class Ma{useSbrkGas;ignoreInstructionGas;registers=new Xn;code=new Uint8Array;mask=Yn.empty();pc=0;gas=uo(ho(0));initialGas=uo(ho(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new bo;memory=new Ko;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=jn.OK;argsDecodingResults=(()=>{const e=new Array(io);return e[Jn.NO_ARGUMENTS]={type:Jn.NO_ARGUMENTS,noOfBytesToSkip:1},e[Jn.ONE_IMMEDIATE]={type:Jn.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new Zn},e[Jn.TWO_REGISTERS]={type:Jn.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[Jn.THREE_REGISTERS]={type:Jn.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Zn,nextPc:0},e[Jn.TWO_REGISTERS_ONE_OFFSET]={type:Jn.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[Jn.TWO_REGISTERS_ONE_IMMEDIATE]={type:Jn.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new Zn},e[Jn.ONE_REGISTER_ONE_IMMEDIATE]={type:Jn.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Zn},e[Jn.ONE_REGISTER_TWO_IMMEDIATES]={type:Jn.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new Zn,secondImmediateDecoder:new Zn},e[Jn.ONE_OFFSET]={type:Jn.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[Jn.TWO_IMMEDIATES]={type:Jn.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Zn,secondImmediateDecoder:new Zn},e[Jn.TWO_REGISTERS_TWO_IMMEDIATES]={type:Jn.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Zn,secondImmediateDecoder:new Zn,firstRegisterIndex:0,secondRegisterIndex:0},e[Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new so},e})();basicBlocks;jumpTable=Ua.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new ro,this.basicBlocks=new yo;const r=new Aa(this.registers),s=new ba(this.registers),i=new ta(this.registers),n=new Ia(this.registers),o=new va(this.registers),a=new Ea(this.registers,this.instructionResult,this.basicBlocks),c=new Ca(this.registers,this.memory,this.instructionResult),l=new ka(this.registers,this.memory,this.instructionResult),h=new xa(this.instructionResult),u=new Ba(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),d=new _a(this.instructionResult),g=new Ra(this.registers,this.memory,this.instructionResult),f=new Oa(this.registers);this.threeRegsDispatcher=new Qo(r,s,i,n,o,f),this.twoRegsOneImmDispatcher=new Fo(r,s,i,n,o,l,c,f),this.twoRegsDispatcher=new Go(o,g,i,f),this.oneRegOneImmOneOffsetDispatcher=new $o(a,c),this.twoRegsOneOffsetDispatcher=new jo(a),this.oneOffsetDispatcher=new qo(a),this.oneRegOneImmDispatcher=new zo(c,l,u),this.twoImmsDispatcher=new Jo(l),this.oneRegTwoImmsDispatcher=new Wo(l),this.noArgsDispatcher=new Yo(h),this.twoRegsTwoImmsDispatcher=new Zo(c,u),this.oneImmDispatcher=new Xo(d),this.oneRegOneExtImmDispatcher=new ea(c)}reset(e,t,r,s,i){const n=new Da(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=uo(r),this.initialGas=uo(r),this.status=jn.OK,this.argsDecoder.reset(this.code,this.mask),this.basicBlocks.reset(this.code,this.mask),this.instructionResult.reset(),void 0!==s?this.registers.copyFrom(s):this.registers.reset(),void 0!==i?this.memory.copyFrom(i):this.memory.reset()}printProgram(){const e=(t=this.code,r=this.mask,t.reduce((e,t,s)=>(r.isInstruction(s)?e.push([no[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===jn.OK;);}nextStep(){this.status===jn.HOST&&(this.status=jn.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??no.TRAP,t=void 0!==no[e],r=mo[e]??mo[no.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=jn.OOG,this.status;const s=ao[e]??Jn.NO_ARGUMENTS,i=this.argsDecodingResults[s];if(this.argsDecoder.fillArgs(this.pc,i),t)switch(this.instructionResult.nextPc=this.pc+i.noOfBytesToSkip,i.type){case Jn.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case Jn.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS:if(this.useSbrkGas&&e===no.SBRK){const e=e=>wo(e)/Hn*16;if(this.gas.sub(ho(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=jn.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case Jn.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case Jn.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case Jn.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=wa.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==wa.FAULT&&this.instructionResult.status!==wa.FAULT_ACCESS||this.gas.sub(mo[no.TRAP]),this.instructionResult.status){case wa.FAULT:this.status=jn.FAULT;break;case wa.HALT:this.status=jn.HALT;break;case wa.PANIC:case wa.FAULT_ACCESS:this.status=jn.PANIC;break;case wa.HOST:this.status=jn.HOST}return this.status}return this.pc=this.instructionResult.nextPc,this.status}getRegisters(){return this.registers}getPC(){return this.pc}setNextPC(e){this.pc=e}getGas(){return this.gas.get()}getGasConsumed(){const e=lo(this.initialGas.get())-lo(this.gas.get());return e<0?this.initialGas.get():lo(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?X(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(Io(e))}}class Pa{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?_.ok(C):e+te(t.length)>Ln?_.error(new xo):this.memory.storeFrom(Gn(Number(e)),t)}loadInto(e,t){return 0===e.length?_.ok(C):t+te(e.length)>Ln?_.error(new xo):this.memory.loadInto(e,Gn(Number(t)))}getMemory(){return this.memory}}class La{registers;constructor(e){this.registers=e}get(e){return te(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class Ha{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,y(null===t&&null!==r||null!==t&&null===r,"`status` and `memorySlice` must not both be null or both be non-null — exactly one must be provided")}static fromStatus(e,t){return new Ha(e,t,null)}static fromMemorySlice(e,t){return new Ha(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class Ka{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===jn.OOG)return Ha.fromStatus(r,e);if(e===jn.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),o=new Uint8Array(n),a=Gn(i);return e.loadInto(o,a).isError?Ha.fromMemorySlice(r,new Uint8Array):Ha.fromMemorySlice(r,o)}return Ha.fromStatus(r,jn.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==jn.HOST)return this.getReturnValue(t,e);y(null!==e.getExitParam(),"We know that the exit param is not null, because the status is `Status.HOST`");const r=e.getExitParam()??-1,s=e.getGasCounter(),i=new La(e.getRegisters()),n=new Pa(e.getMemory()),o=this.hostCalls.get(zn(r)),a="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(a))return Ha.fromStatus(e.getGasConsumed(),jn.OOG);if(await o.execute(s,i,n)===Wn.Halt)return t=jn.HALT,this.getReturnValue(t,e);e.runProgram(),t=e.getStatus()}}async runProgram(e,t,r,s,i){const n=await this.pvmInstanceManager.getInstance();n.reset(e,t,r,s,i);try{return await this.execute(n)}finally{this.pvmInstanceManager.releaseInstance(n)}}}class Va{instances=[];waitingQueue=[];constructor(e){for(let t=0;t<e;t++)this.instances.push(new Ma({useSbrkGas:!1,ignoreInstructionGas:!0}))}async getInstance(){const e=this.instances.pop();return void 0!==e?Promise.resolve(e):new Promise(e=>{this.waitingQueue.push(e)})}releaseInstance(e){const t=this.waitingQueue.shift();if(void 0!==t)return t(e);this.instances.push(e)}}const Qa={NONE:te(0xffffffffffffffffn),WHAT:te(0xfffffffffffffffen),OOB:te(0xfffffffffffffffdn),WHO:te(0xfffffffffffffffcn),FULL:te(0xfffffffffffffffbn),CORE:te(0xfffffffffffffffan),CASH:te(0xfffffffffffffff9n),LOW:te(0xfffffffffffffff8n),HUH:te(0xfffffffffffffff7n),OK:te(0n)},Fa=X(2**32-1),Ga=te(Fa),$a=pr(2**32-1);function ja(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:qa(s)}function qa(e){const{lower:t,upper:r}=(e=>{const t=e>>32n;return{lower:Number(e&2n**32n-1n),upper:Number(t)}})(e);return 0===r?pr(t):null}function za(e,t){y(t.length>=4,"Not enough space in the destination."),t.set(ie(e))}function Wa(e){return e>Ga?Fa:X(Number(e))}const Ja=Gs.new(void 0,"host-calls");class Ya{hostCalls=new Map;missing=new Za;constructor(...e){for(const t of e)y(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){const t=this.hostCalls.get(e)??this.missing;return Ja.trace(`[${t.currentServiceId}] PVM invoking ${e} (${t.constructor.name}:${t.index})`),t}}class Za{index=zn(2**32-1);gasCost=co(10);currentServiceId=$a;execute(e,t,r){return t.set(7,Qa.WHAT),Promise.resolve(void 0)}}const Xa=4096,ec=65536,tc=2**24,rc=4278059008,sc=4278124544;function ic(e){return Xa*Math.ceil(e/Xa)}class nc extends w{start;end;data;static from({start:e,end:t,data:r}){return new nc(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class oc extends w{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class ac extends w{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function cc(e,t,r=null){return new nc(e,t,r)}class lc{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?hc(e):{code:e},{code:n,memory:o,registers:a}=function(e,t){const r=ae.fromBlob(e),s=r.u24(),i=r.u24(),n=m(t.length,t.length<=tc,"Incorrect arguments length"),o=m(s,s<=tc,"Incorrect readonly segment length"),a=m(i,i<=tc,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),h=r.bytes(o).raw,u=r.bytes(a).raw,d=r.u32(),g=r.bytes(d).raw;r.finish();const f=ec+ic(o),p=131072+(y=o,ec*Math.ceil(y/ec));var y;const b=p+ic(a),A=p+ic(a)+c*Xa,I=rc-ic(l),v=rc,w=sc,S=w+ic(n),E=S+ic(n);function C(e){return!1!==e}const k=[o>0&&cc(65536,f,h),n>0&&cc(w,S,t),S<E&&cc(S,E)].filter(C),x=[a>0&&cc(p,b,u),b<A&&cc(b,A),I<v&&cc(I,v)].filter(C);return new ac(g,new oc(k,x,A,I),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(rc),t[7]=BigInt(sc),t[8]=BigInt(e),t}(t.length))}(s,t),c=new Xn;c.copyFrom(a);const l=new Vo;for(const{start:e,end:t,data:r}of o.readable){const s=Gn(e),i=Gn(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of o.writeable){const s=Gn(e),i=Gn(t);l.setWriteablePages(s,i,r??new Uint8Array)}const h=Gn(o.sbrkIndex),u=$n(o.heapEnd),d=l.finalize(h,u);return new lc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?hc(e):{code:e},i=new Xn,n=new Ko;return new lc(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function hc(e){const t=ae.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var uc,dc,gc;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(uc||(uc={}));class fc{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return ot(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return ot(this.keccakHasher,[e,t,r])}header(e){return new Oe(He(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=He(e.report.encoded(),this.allocator).asOpaque();return O.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=ge.encodeObject(we.sequenceVarLen(Mi),t,this.context),s=He(e.tickets.encoded(),this.allocator).asOpaque(),i=He(e.preimages.encoded(),this.allocator).asOpaque(),n=He(r,this.allocator).asOpaque(),o=He(e.assurances.encoded(),this.allocator).asOpaque(),a=He(e.disputes.encoded(),this.allocator).asOpaque(),c=O.blobFromParts([s.raw,i.raw,n.raw,o.raw,a.raw]);return new Ue(He(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Rr.Codec,e)}encode(e,t){const r=ge.encodeObject(e,t,this.context);return new Ue(He(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(dc||(dc={}));class pc{state;constructor(e){this.state=e}integrate(e){for(let t=1;t<e.preimages.length;t++){const r=e.preimages[t-1],s=e.preimages[t];if(!(r.requester<s.requester)&&(r.requester>s.requester||s.blob.compare(r.blob).isLessOrEqual()))return _.error(dc.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=He(i).asOpaque(),o=this.state.getService(t);if(null===o)return _.error(dc.AccountNotFound);const a=o.hasPreimage(n),c=o.getLookupHistory(n,X(i.length));if(a||null===c||!gi.isRequested(c))return _.error(dc.PreimageUnneeded);s.push(mi.provide({serviceId:t,preimage:hi.create({hash:n,blob:i}),slot:r}))}return _.ok({preimages:s})}}class yc{spec;importer;toImport=ut.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?u.Greater:r>0?u.Less:u.Equal});lastEpoch=br(2**32-1);constructor(e,t){this.spec=e,this.importer=t}tryToReadTimeSlot(e){try{return e.header.view().timeSlotIndex.materialize()}catch{return null}}isCurrentEpoch(e){const t=Math.floor(e/this.spec.epochLength);return this.lastEpoch===t}startPreverification(){for(const e of this.toImport)this.isCurrentEpoch(e.timeSlot)&&(e.seal=this.importer.preverifySeal(e.timeSlot,e.block))}push(e){const t=this.tryToReadTimeSlot(e);if(null===t)return null;const r={timeSlot:t,block:e,seal:this.isCurrentEpoch(t)?this.importer.preverifySeal(t,e):Promise.resolve(null)};return this.toImport.insert(r),t}shift(){const e=this.toImport.pop();if(void 0!==e){const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=br(t),r&&this.startPreverification()}return e}}!function(e){e[e.ParentNotFound=0]="ParentNotFound",e[e.InvalidTimeSlot=1]="InvalidTimeSlot",e[e.InvalidExtrinsic=2]="InvalidExtrinsic",e[e.StateRootNotFound=3]="StateRootNotFound",e[e.InvalidStateRoot=4]="InvalidStateRoot",e[e.AlreadyImported=5]="AlreadyImported"}(gc||(gc={}));const mc=U.zero(Re).asOpaque();class bc{hasher;blocks;constructor(e,t){this.hasher=e,this.blocks=t}async verifyBlock(e){const t=e.header.view(),r=this.hasher.header(t);if(null!==this.blocks.getHeader(r.hash))return _.error(gc.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(mc)){const e=this.blocks.getHeader(s);if(null===e)return _.error(gc.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return _.error(gc.InvalidTimeSlot,`Invalid time slot index: ${r}, expected > ${i}`)}const i=t.extrinsicHash.materialize(),n=this.hasher.extrinsic(e.extrinsic.view());if(!i.isEqualTo(n.hash))return _.error(gc.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const o=t.priorStateRoot.materialize(),a=this.blocks.getPostStateRoot(s);return null===a?_.error(gc.StateRootNotFound,`Posterior state root ${s.toString()} not found`):o.isEqualTo(a)?_.ok(r.hash):_.error(gc.InvalidStateRoot,`Invalid prior state root: ${o.toString()}, expected ${a.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var Ac;function Ic(e,t){for(let r=1;r<e.length;r++)if(e[r-1][t].compare(e[r][t]).isGreaterOrEqual())return!1;return!0}!function(e){e.AlreadyJudged="already_judged",e.BadVoteSplit="bad_vote_split",e.VerdictsNotSortedUnique="verdicts_not_sorted_unique",e.JudgementsNotSortedUnique="judgements_not_sorted_unique",e.CulpritsNotSortedUnique="culprits_not_sorted_unique",e.FaultsNotSortedUnique="faults_not_sorted_unique",e.NotEnoughCulprits="not_enough_culprits",e.NotEnoughFaults="not_enough_faults",e.CulpritsVerdictNotBad="culprits_verdict_not_bad",e.FaultVerdictWrong="fault_verdict_wrong",e.OffenderAlreadyReported="offender_already_reported",e.BadJudgementAge="bad_judgement_age",e.BadValidatorIndex="bad_validator_index",e.BadSignature="bad_signature",e.BadGuarantorKey="bad_guarantor_key",e.BadAuditorKey="bad_auditor_key"}(Ac||(Ac={}));const vc=O.blobFromString("jam_valid").raw,wc=O.blobFromString("jam_invalid").raw,Sc=O.blobFromString("jam_guarantee").raw;function Ec({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:O.blobFromParts(Sc,r.raw)}}function Cc({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?vc:wc;return{key:s,signature:r,message:O.blobFromParts(i,e.raw)}}function kc(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?vc:wc;return{key:r,signature:i,message:O.blobFromParts(n,t.raw)}}class xc{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!Ic(e.culprits,"key"))return _.error(Ac.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return _.error(Ac.OffenderAlreadyReported);if(!s.has(i))return _.error(Ac.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(o))return _.error(Ac.CulpritsVerdictNotBad);const a=r.culprits[n];if(!a?.isValid)return _.error(Ac.BadSignature)}return _.ok(null)}verifyFaults(e,t,r,s){if(!Ic(e.faults,"key"))return _.error(Ac.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o,wasConsideredValid:a}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return _.error(Ac.OffenderAlreadyReported);if(!s.has(i))return _.error(Ac.BadAuditorKey);if(a){const e=t.toAddToGoodSet.findExact(o),r=t.toAddToBadSet.findExact(o);if(void 0!==e||void 0===r)return _.error(Ac.FaultVerdictWrong)}if(!r.faults[n].isValid)return _.error(Ac.BadSignature)}return _.ok(null)}verifyVerdicts(e,t){if(!Ic(e.verdicts,"workReportHash"))return _.error(Ac.VerdictsNotSortedUnique);if(e.verdicts.some(e=>!function(e){for(let t=1;t<e.length;t++)if(e[t-1].index>=e[t].index)return!1;return!0}(e.votes)))return _.error(Ac.JudgementsNotSortedUnique);const r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);let s=0;for(const{votesEpoch:i,votes:n}of e.verdicts){if(i!==r&&i+1!==r)return _.error(Ac.BadJudgementAge);const e=i===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const{index:r}of n){const i=e[r]?.ed25519;if(void 0===i)return _.error(Ac.BadValidatorIndex);if(!t.judgements[s].isValid)return _.error(Ac.BadSignature);s+=1}}return _.ok(null)}verifyIfAlreadyJudged(e){for(const t of e.verdicts){const e=this.state.disputesRecords.goodSet.findExact(t.workReportHash),r=this.state.disputesRecords.badSet.findExact(t.workReportHash),s=this.state.disputesRecords.wonkySet.findExact(t.workReportHash);if(void 0!==e||void 0!==r||void 0!==s)return _.error(Ac.AlreadyJudged)}return _.ok(null)}calculateVotesForWorkReports(e){const t=at.new();for(const r of e.verdicts){const e=r.votes,s=r.workReportHash;let i=0;for(const{isWorkReportValid:t}of e)t&&(i+=1);t.set(s,i)}return t}verifyVotesForWorkReports(e,t){for(const[r,s]of e)if(s===this.chainSpec.validatorsSuperMajority){const e=t.faults.find(e=>e.workReportHash.isEqualTo(r));if(void 0===e)return _.error(Ac.NotEnoughFaults)}else if(0===s){const e=t.culprits.find(e=>e.workReportHash.isEqualTo(r)),s=t.culprits.findLast(e=>e.workReportHash.isEqualTo(r));if(e===s)return _.error(Ac.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return _.error(Ac.BadVoteSplit);return _.ok(null)}getDisputesRecordsNewItems(e){const t=[],r=[],s=[];for(const[i,n]of e)n>=this.chainSpec.validatorsSuperMajority?t.push(i):0===n?r.push(i):n>=this.chainSpec.thirdOfValidators&&s.push(i);return{toAddToGoodSet:dt.fromArray(ei,t),toAddToBadSet:dt.fromArray(ei,r),toAddToWonkySet:dt.fromArray(ei,s)}}getClearedCoreAssignment(e){const t=this.state.availabilityAssignment.slice();for(let r=0;r<t.length;r++){const s=t[r];if(null!==s){const i=e.get(s.workReport.hash);void 0!==i&&i<this.chainSpec.validatorsSuperMajority&&(t[r]=null)}}return Ws(t,this.chainSpec)}getOffenders(e){const t=[];for(const{key:r}of e.culprits)t.push(r);for(const{key:r}of e.faults)t.push(r);return t}getUpdatedDisputesRecords(e,t){const r=ut.fromArray(ei,t);return Xs.create({goodSet:dt.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:dt.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:dt.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:dt.fromTwoSortedCollections(this.state.disputesRecords.punishSet,r)})}prepareSignaturesToVerification(e){const t={culprits:[],judgements:[],faults:[]},r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);for(const{votesEpoch:s,votes:i,workReportHash:n}of e.verdicts){const e=s===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const r of i){const s=e[r.index];if(void 0===s)return _.error(Ac.BadValidatorIndex);const i=s.ed25519;t.judgements.push(kc(r,n,i))}}return t.culprits=e.culprits.map(Ec),t.faults=e.faults.map(Cc),_.ok(t)}getValidatorKeys(){const e=this.state.disputesRecords.punishSet,t=this.state.currentValidatorData.map(e=>e.ed25519),r=this.state.previousValidatorData.map(e=>e.ed25519),s=t.concat(r).filter(t=>!e.has(t));return ct.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return _.error(t.error);const r=async function(e){const t={culprits:[],faults:[],judgements:[]},r=Object.entries(e);for(const[e,s]of r)t[e]=(await ir(s)).map((e,t)=>({isValid:e,signature:s[t].signature}));return Promise.resolve(t)}(t.ok),s=this.calculateVotesForWorkReports(e),i=this.getDisputesRecordsNewItems(s),n=await r,o=this.getValidatorKeys(),a=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,o),this.verifyFaults(e,i,n,o),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(a?.isError)return _.error(a.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),h=this.getClearedCoreAssignment(s);return _.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:h}})}}const Bc=O.blobFromString("jam_entropy").raw,_c=O.blobFromString("jam_fallback_seal").raw,Rc=O.blobFromString("jam_ticket_seal").raw;var Oc;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(Oc||(Oc={}));const Uc=async function(e,t,r,s,i,n){const o=O.blobFromParts(t.map(e=>e.raw)).raw,a=await e.verifySeal(o,r,s.raw,i.raw,n.raw);return a[0]===Oc.Error?_.error(null):_.ok(U.fromBlob(a.subarray(1),Re).asOpaque())},Tc=async function(e,t,r,s){const i=s.length+Rc.length+1,n=O.blobFromParts(r.map(e=>O.blobFromParts([e.signature.raw,Rc,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,o=O.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(o,n,i);return Array.from(O.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===Oc.Ok,entropyHash:U.fromBlob(e.raw.subarray(1,33),Re).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:U.zero(Re).asOpaque()}));throw e}},Nc=async function(e,t){const r=O.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===Oc.Error?_.error(null):_.ok(U.fromBlob(s.subarray(1),Be).asOpaque())};class Dc{runInternal;state;static new(e,t){return new Dc(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===$s.parentPort)throw new Error("This method is meant to be run inside a worker thread!");$s.parentPort.once("close",()=>{process.exit(0)}),$s.parentPort.once("message",e=>{this.listenTo(e),$s.parentPort?.postMessage("ready")})}listenTo(e){e.once("close",()=>{e.removeAllListeners(),process.exit(0)}),e.on("message",t=>{const{params:r}=t;this.run(r).then(t=>{const r=_.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=_.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class Mc{workers;maxWorkers;workerPath;static async initialize(e,t){y(t.maxWorkers>0,"Max workers has to be positive."),y(t.minWorkers<=t.maxWorkers,"Min workers has to be lower or equal to max workers.");const r=[];for(let s=0;s<t.minWorkers;s++)r.push(await Pc(e));return new Mc(r,t.maxWorkers,e)}freeWorkerIndices=[];taskQueue=[];isDestroyed=!1;isWorkerInitializing=!1;constructor(e,t,r){this.workers=e,this.maxWorkers=t,this.workerPath=r;for(let t=0;t<e.length;t++)this.freeWorkerIndices.push(t)}async initNewWorker(e=()=>{}){this.workers.length>=this.maxWorkers?console.warn(`Task queue has ${this.taskQueue.length} pending items and we can't init any more workers.`):this.isWorkerInitializing||(this.isWorkerInitializing=!0,this.workers.push(await Pc(this.workerPath)),this.freeWorkerIndices.push(this.workers.length-1),this.isWorkerInitializing=!1,e())}async destroy(){for(const e of this.workers)e.port.close(),await e.worker.terminate();this.workers.length=0,this.isDestroyed=!0}async run(e){return new Promise((t,r)=>{this.isDestroyed?r("pool destroyed"):(this.taskQueue.push({params:e,resolve:t,reject:r}),this.processEntryFromTaskQueue())})}processEntryFromTaskQueue(){const e=this.freeWorkerIndices.pop();if(void 0===e)return void(this.taskQueue.length>5&&this.initNewWorker(()=>{this.processEntryFromTaskQueue()}));const t=this.taskQueue.pop();void 0!==t?this.workers[e].runTask(t,()=>{this.freeWorkerIndices.push(e),this.processEntryFromTaskQueue()}):this.freeWorkerIndices.push(e)}}async function Pc(e){const{port1:t,port2:r}=new MessageChannel,s=new $s.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new Lc(s,r)}class Lc{worker;port;constructor(e,t){this.worker=e,this.port=t}runTask(e,t){const r={params:e.params};this.port.once("message",r=>{r.isOk?e.resolve(r.ok):e.reject(new Error(r.error)),t()}),this.port.postMessage(r,r.params.getTransferList())}}var Hc;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(Hc||(Hc={}));class Kc{data;constructor(e){this.data=e}getTransferList(){return[]}}class Vc{params;constructor(e){this.params=e}getTransferList(){return[]}}const Qc=Dc.new(e=>{const t=e.params,r=t.method;return r===Hc.RingCommitment?Promise.resolve(new Kc((0,ke.hc)(t.keys))):r===Hc.BatchVerifyTickets?Promise.resolve(new Kc((0,ke.ZJ)(t.keys,t.ticketsData,t.contextLength))):r===Hc.VerifySeal?Promise.resolve(new Kc((0,ke.KG)(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void b(r)},null);class Fc{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=Bs().cpus().length;return new Fc(e?Qc:await Mc.initialize(new URL(o(884),o.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new Vc({method:Hc.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new Vc({method:Hc.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new Vc({method:Hc.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const Gc=(e,t)=>F(e.id,t.id);var $c,jc,qc,zc,Wc,Jc,Yc;!function(e){e[e.IncorrectData=1]="IncorrectData",e[e.BadSlot=2]="BadSlot",e[e.UnexpectedTicket=3]="UnexpectedTicket",e[e.BadTicketOrder=4]="BadTicketOrder",e[e.BadTicketProof=5]="BadTicketProof",e[e.BadTicketAttempt=6]="BadTicketAttempt",e[e.DuplicateTicket=7]="DuplicateTicket"}($c||($c={}));class Zc{chainSpec;state;bandersnatch;constructor(e,t,r=Fc.new({synchronous:!0})){this.chainSpec=e,this.state=t,this.bandersnatch=r}isEpochChanged(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)>t}isSameEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t}isNextEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t+1}getSlotPhaseIndex(e){return e%this.chainSpec.epochLength}getEntropy(e,t){const[r,...s]=this.state.entropy,i=Le([r.raw,t]).asOpaque();return this.isEpochChanged(e)?ht.new([i,r,s[0],s[1]],4):ht.new([i,...s],4)}async getValidatorKeys(e){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return _.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const t=this.state.disputesRecords.punishSet,r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?ii.create({bandersnatch:U.zero(xe).asOpaque(),ed25519:U.zero(rr).asOpaque(),bls:e.bls,metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await Nc(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?_.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):_.error($c.IncorrectData)}outsideInSequencer(e){const t=e.length,r=new Array(t),s=Math.floor(t/2);t%2==1&&(r[s]=e[s]);for(let i=0;i<s;i+=1)r[2*i]=e[i],r[2*i+1]=e[t-i-1];return vr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=X(0);n<r;n++){const r=ie(n),o=Le([e.raw,r]).raw,a=ae.fromBlob(o).u32()%i;s.push(t[a].bandersnatch)}return vr(s,this.chainSpec)}getSlotKeySequence(e,t,r){const s=this.getSlotPhaseIndex(this.state.timeslot);return this.isNextEpoch(e)&&s>=this.chainSpec.contestLength&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?ai.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:ai.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return Gr.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>Fr.create(e))})}verifyTickets(e){const t=e.length;for(let r=1;r<t;r++){const t=e[r-1].id.compare(e[r].id);if(t.isEqual())return _.error($c.DuplicateTicket);if(t.isGreater())return _.error($c.BadTicketOrder)}return _.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await Tc(await this.bandersnatch,r.map(e=>e.bandersnatch),t,s),n=t.map((e,t)=>({id:i[t].entropyHash,attempt:e.attempt}));if(!i.every(e=>e.isValid))return _.error($c.BadTicketProof);const o=this.verifyTickets(n);if(o.isError)return _.error(o.error);if(this.isEpochChanged(e))return _.ok(n);const a=dt.fromSortedArray(Gc,this.state.ticketsAccumulator),c=dt.fromSortedArray(Gc,n),l=dt.fromTwoSortedCollections(a,c);return a.length+c.length!==l.length?_.error($c.DuplicateTicket):_.ok(l.array.slice(0,this.chainSpec.epochLength))}getTicketsMark(e){const t=this.getSlotPhaseIndex(this.state.timeslot),r=this.getSlotPhaseIndex(e);return this.isSameEpoch(e)&&t<this.chainSpec.contestLength&&this.chainSpec.contestLength<=r&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?this.outsideInSequencer(this.state.ticketsAccumulator):null}isExtrinsicLengthValid(e,t){return this.getSlotPhaseIndex(e)<this.chainSpec.contestLength?t.length<=this.chainSpec.maxTicketsPerExtrinsic:0===t.length}areTicketAttemptsValid(e){const t=e.length;for(let r=0;r<t;r++)if(e[r].attempt>=this.chainSpec.ticketsPerValidator)return!1;return!0}getSafroleSealState(e){const t=this.isEpochChanged(e),r=t?this.state.nextValidatorData:this.state.currentValidatorData,s=this.state.entropy[t?1:2];return{currentValidatorData:r,currentEntropy:this.state.entropy[t?2:3],sealingKeySeries:this.getSlotKeySequence(e,r,s)}}async transition(e){if(this.state.timeslot>=e.slot)return _.error($c.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return _.error($c.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return _.error($c.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot);if(t.isError)return _.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,o=this.getEntropy(e.slot,e.entropy),a=this.getSlotKeySequence(e.slot,s,o[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,o[2]);if(c.isError)return _.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:o,sealingKeySeries:a,ticketsAccumulator:c.ok},h={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return _.ok(h)}}!function(e){e[e.InvalidValidatorIndex=0]="InvalidValidatorIndex",e[e.InvalidValidator=1]="InvalidValidator",e[e.InvalidTicket=2]="InvalidTicket",e[e.IncorrectSeal=3]="IncorrectSeal",e[e.IncorrectEntropySource=4]="IncorrectEntropySource"}(jc||(jc={}));class Xc{bandersnatch;constructor(e=Fc.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=O.blobFromParts(Bc,r.ok.raw),i=await Uc(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,O.blobFromNumbers([]));return i.isError?_.error(jc.IncorrectEntropySource):_.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return _.error(jc.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),o=t.sealingKeySeries,a=t.currentEntropy;return o.kind===ni.Tickets?await this.verifySealWithTicket(o.tickets,n,a,r,s,e):await this.verifySealWithKeys(o.keys,i,n,a,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const o=t%e.length,{id:a,attempt:c}=e[o],l=O.blobFromParts(Rc,r.raw,new Uint8Array([c])),h=await Uc(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,$r(n));return h.isError?_.error(jc.IncorrectSeal):a.isEqualTo(h.ok)?_.ok(h.ok):_.error(jc.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,o){if(!e[r%e.length].isEqualTo(t.bandersnatch))return _.error(jc.InvalidValidator);const a=O.blobFromParts(_c,s.raw),c=await Uc(await this.bandersnatch,i.map(e=>e.bandersnatch),n,o.seal.materialize(),a,$r(o));return c.isError?_.error(jc.IncorrectSeal):_.ok(c.ok)}}function el(e){if(e.length===qc.Requested)return{status:qc.Requested};if(e.length===qc.Available)return{status:qc.Available,data:[e[0]]};if(e.length===qc.Unavailable)return{status:qc.Unavailable,data:[e[0],e[1]]};if(e.length===qc.Reavailable)return{status:qc.Reavailable,data:[e[0],e[1],e[2]]};throw new Error(`Invalid slots length: ${e.length}`)}!function(e){e[e.Requested=0]="Requested",e[e.Available=1]="Available",e[e.Unavailable=2]="Unavailable",e[e.Reavailable=3]="Reavailable"}(qc||(qc={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(zc||(zc={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(Wc||(Wc={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(Jc||(Jc={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(Yc||(Yc={}));class tl{source;destination;amount;memo;gas;static Codec=we.Class(tl,{source:we.u32.asOpaque(),destination:we.u32.asOpaque(),amount:we.u64,memo:we.bytes(128),gas:we.u64.asOpaque()});constructor(e,t,r,s,i){this.source=e,this.destination=t,this.amount=r,this.memo=s,this.gas=i}static create({source:e,destination:t,amount:r,memo:s,gas:i}){return new tl(e,t,r,s,i)}}class rl{services;transfers;authorizationQueues=new Map;yieldedRoot=null;validatorsData=null;privilegedServices=null;constructor(e,t){this.services=e,this.transfers=t}static empty(){return new rl({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new rl(e,[])}static copyFrom(e){const t={servicesUpdates:[...e.services.servicesUpdates],servicesRemoved:[...e.services.servicesRemoved],preimages:[...e.services.preimages],storage:[...e.services.storage]},r=[...e.transfers],s=new rl(t,r);for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return s.yieldedRoot=e.yieldedRoot,s.validatorsData=null===e.validatorsData?null:[...e.validatorsData],s.privilegedServices=null===e.privilegedServices?null:ri.create({...e.privilegedServices}),s}}class sl{chainSpec;state;currentServiceId;currentTimeslot;updatedState;checkpointedState=null;nextNewServiceId;constructor(e,t,r,s,i,n=rl.empty()){if(this.chainSpec=e,this.state=t,this.currentServiceId=r,this.currentTimeslot=i,this.updatedState=n,this.nextNewServiceId=this.getNextAvailableServiceId(s),null===this.state.getService(this.currentServiceId))throw new Error(`Invalid state initialization. Service info missing for ${this.currentServiceId}.`)}getStateUpdates(){return[this.updatedState,this.checkpointedState]}getNextNewServiceId(){return this.nextNewServiceId}getCurrentServiceInfo(){const e=this.updatedState.services.servicesUpdates.find(e=>e.serviceId===this.currentServiceId);if(void 0!==e)return e.action.account;const t=this.state.getService(this.currentServiceId);return m(t,null!==t,"Service existence in state validated in constructor.").getInfo()}getServiceInfo(e){if(null===e)return null;if(e===this.currentServiceId)return this.getCurrentServiceInfo();const t=this.updatedState.services.servicesRemoved.some(t=>t===e);if(t)return null;const r=this.updatedState.services.servicesUpdates.find(t=>t.serviceId===e&&t.action.kind===pi.Create);if(void 0!==r)return r.action.account;const s=this.state.getService(e);return null===s?null:s.getInfo()}getUpdatedPreimageStatus(e,t){const r=this.updatedState.services.preimages.findLast(r=>r.serviceId===this.currentServiceId&&r.hash.isEqualTo(e)&&BigInt(r.length)===t),s=()=>{const r=this.state.getService(this.currentServiceId),s=il(t);if(null===s||null===r)return null;const i=r.getLookupHistory(e,s);return null===i?null:new gi(e,s,i)};if(void 0===r)return s();const{action:i}=r;switch(i.kind){case fi.Provide:return new gi(e,r.length,di([this.currentTimeslot]));case fi.Remove:{const t=s();return null===t?null:new gi(e,t.length,di([...t.slots,this.currentTimeslot]))}case fi.UpdateOrAdd:return i.item}b(i)}isPreviousCodeExpired(e,t,r){const s=this.state.getService(e),i=il(r),n=null===s||null===i?null:s.getLookupHistory(t,i),o=null===n?null:el(n);if(o?.status!==qc.Unavailable)return[!1,"wrong status"];const a=this.currentTimeslot,c=o.data[1]<a-this.chainSpec.preimageExpungePeriod;return[c,c?"":"not expired"]}hasExistingPreimage(e,t){if(null===e)return!1;if(void 0!==this.updatedState.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}addPreimageUpdate(e){this.updatedState.services.preimages.push(e)}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=pr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.getUpdatedPreimageStatus(e,t);return null===r?null:el(r.slots)}requestPreimage(e,t){const r=this.getUpdatedPreimageStatus(e,t);if(null!==r){const e=r.slots.length;if(e===qc.Requested)return _.error(zc.AlreadyRequested);if(e===qc.Available||e===qc.Reavailable)return _.error(zc.AlreadyAvailable);y(e===qc.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,o=t-BigInt(r?.length??0),a=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(o)+(i?0n:81n);y(a>=0,`storageUtilisationCount has to be a positive number, got: ${a}`),y(c>=0,`storageUtilisationBytes has to be a positive number, got: ${c}`);const l=!ee(a),h=!re(c),u=this.updateServiceStorageUtilisation({overflow:l,value:l?X(0):a},{overflow:h,value:h?te(0):c},s);if(u.isError)return _.error(zc.InsufficientFunds,u.details);const d=Wa(t);return null===r?this.addPreimageUpdate(mi.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new gi(e,d,di([]))})):this.addPreimageUpdate(mi.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new gi(e,d,di([...r.slots,this.currentTimeslot]))})),_.ok(C)}updateServiceStorageUtilisation(e,t,r){if(e.overflow||t.overflow)return _.error("insufficient funds");const s=li.calculateThresholdBalance(e.value,t.value);return r.balance<s?_.error("insufficient funds"):(this.updateCurrentServiceInfo(li.create({...r,storageUtilisationBytes:t.value,storageUtilisationCount:e.value})),_.ok(C))}updateCurrentServiceInfo(e){const t=this.updatedState.services.servicesUpdates.findIndex(e=>e.serviceId===this.currentServiceId),r=-1===t?0:1;this.updatedState.services.servicesUpdates.splice(t,r,bi.update({serviceId:this.currentServiceId,serviceInfo:e}))}forgetPreimage(e,t){const r=this.currentServiceId,s=this.getUpdatedPreimageStatus(e,t);if(null===s)return _.error(null);const i=el(s.slots);if(i.status===qc.Requested)return this.addPreimageUpdate(mi.remove({serviceId:r,hash:s.hash,length:s.length})),_.ok(C);const n=this.currentTimeslot;return i.status===qc.Unavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.addPreimageUpdate(mi.remove({serviceId:r,hash:s.hash,length:s.length})),_.ok(C)):_.error(null):i.status===qc.Available?(this.addPreimageUpdate(mi.updateOrAdd({serviceId:r,lookupHistory:new gi(s.hash,s.length,di([i.data[0],n]))})),_.ok(C)):i.status===qc.Reavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.addPreimageUpdate(mi.updateOrAdd({serviceId:r,lookupHistory:new gi(s.hash,s.length,di([i.data[2],n]))})),_.ok(C)):_.error(null):void b(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return _.error(Wc.DestinationNotFound);if(r<n.onTransferMinGas)return _.error(Wc.GasTooLow);const o=i.balance-t;return o<li.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes)?_.error(Wc.BalanceBelowThreshold):(this.updatedState.transfers.push(tl.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updateCurrentServiceInfo(li.create({...i,balance:te(o)})),_.ok(C))}newService(e,t,r,s){const i=this.nextNewServiceId,n=X(2),o=se(te(81),t),a=Wa(t),c=li.calculateThresholdBalance(n,o.value),l=this.getCurrentServiceInfo(),h=li.calculateThresholdBalance(l.storageUtilisationCount,l.storageUtilisationBytes),u=l.balance-c;return u<h||o.overflow?_.error("insufficient funds"):(this.updatedState.services.servicesUpdates.push(bi.create({serviceId:i,serviceInfo:li.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),lookupHistory:new gi(e.asOpaque(),a,di([]))})),this.updateCurrentServiceInfo(li.create({...l,balance:te(u)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return pr(256+(e-256+42+t)%t)}(i)),_.ok(i))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updateCurrentServiceInfo(li.create({...s,codeHash:e,accumulateMinGas:yr(t),onTransferMinGas:yr(r)}))}updateValidatorsData(e){this.updatedState.validatorsData=e}checkpoint(){this.checkpointedState=rl.copyFrom(this.updatedState)}updateAuthorizationQueue(e,t){this.updatedState.authorizationQueues.set(e,t)}updatePrivilegedServices(e,t,r,s){this.updatedState.privilegedServices=ri.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>ti.create({service:e,gasLimit:t}))})}yield(e){this.updatedState.yieldedRoot=e}providePreimage(e,t){const r=null===e?null:this.state.getService(e);if(null===r||null===e)return _.error(Yc.ServiceNotFound);const s=He(t).asOpaque();if(e===this.currentServiceId){const e=this.getUpdatedPreimageStatus(s,te(t.length));if(null===e||!gi.isRequested(e))return _.error(Yc.WasNotRequested)}else{const e=r.getLookupHistory(s,X(t.length));if(null===e||!gi.isRequested(e))return _.error(Yc.WasNotRequested)}return this.hasExistingPreimage(e,s)?_.error(Yc.AlreadyProvided):(this.addPreimageUpdate(mi.provide({serviceId:e,preimage:hi.create({hash:s,blob:t}),slot:this.currentTimeslot})),_.ok(C))}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return _.error(Jc.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=U.zero(Re).asOpaque();if(za(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return _.error(Jc.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return _.error(Jc.InvalidPreimage,"Too many storage items");const n=te(81),o=te(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,n)-n),[a,c]=this.isPreviousCodeExpired(e,t,o);if(!a)return _.error(Jc.InvalidPreimage,`Previous code available: ${c}`);const l=se(s.balance,r.balance);return l.overflow?_.error(Jc.InvalidService,"Balance overflow"):(this.updateCurrentServiceInfo(li.create({...s,balance:l.value})),this.updatedState.services.servicesRemoved.push(e),_.ok(C))}replaceOrAddStorageUpdate(e,t){const r=null===t?Ai.remove({serviceId:this.currentServiceId,key:e}):Ai.set({serviceId:this.currentServiceId,storage:ui.create({key:e,value:t})}),s=this.updatedState.services.storage.findIndex(t=>t.serviceId===r.serviceId&&t.key.isEqualTo(e)),i=-1===s?0:1;this.updatedState.services.storage.splice(s,i,r)}read(e,t){if(null===e)return null;if(this.currentServiceId===e){const r=this.updatedState.services.storage.find(r=>r.serviceId===e&&r.key.isEqualTo(t));if(void 0!==r)return r.value}const r=this.state.getService(e);return r?.getStorage(t)??null}write(e,t){const r=this.read(this.currentServiceId,e),s=null===r&&null!==t,i=null!==r&&null===t,n=s?1:i?-1:0,o=(t?.length??0)-(r?.length??0),a=s?BigInt(Re):i?BigInt(-32):0n,c=this.getCurrentServiceInfo(),l=c.storageUtilisationCount+n,h=c.storageUtilisationBytes+BigInt(o)+a;y(l>=0,`storageUtilisationCount has to be a positive number, got: ${l}`),y(h>=0,`storageUtilisationBytes has to be a positive number, got: ${h}`);const u=!ee(l),d=!re(h),g=this.updateServiceStorageUtilisation({overflow:u,value:u?X(0):l},{overflow:d,value:d?te(0):h},c);return g.isError?_.error("full",g.details):(this.replaceOrAddStorageUpdate(e,t),_.ok(C))}readSnapshotLength(e){const t=this.state.getService(this.currentServiceId);return t?.getStorage(e)?.length??null}lookup(e,t){if(null===e)return null;const r=this.updatedState.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t));if(void 0!==r&&r.action.kind===fi.Provide)return r.action.preimage.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}}function il(e){return e>=2n**32n?null:X(Number(e))}function nl(e){const t=e.map(e=>e.workPackageSpec.hash);return ct.from(t)}const ol=we.object({serviceId:we.u32.asOpaque(),entropy:we.bytes(Re).asOpaque(),timeslot:we.u32.asOpaque()}),al=we.object({serviceId:we.u32.convert(e=>e,e=>e),gas:we.u64.convert(e=>te(e),e=>yr(e))});class cl{currentServiceId;index=zn(0);gasCost=co(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,te(e.get())),Promise.resolve(void 0)}}const ll=he(ii.Codec.sizeHint),hl=e=>te(e);var ul,dl,gl;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(ul||(ul={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(dl||(dl={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class fl{currentServiceId;fetch;index=zn(18);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=te(s?.length??0),o=oe(t.get(8),n),a=oe(t.get(9),te(n-o)),c=null===s?new Uint8Array:s.raw.subarray(Number(o),Number(o+a));if(r.storeFrom(i,c).isError)return Wn.Panic;t.set(7,null===s?Qa.NONE:n)}getValue(e){const t=Wa(e.get(10));if(t===gl.Constants)return this.fetch.constants();if(t===gl.Entropy)return this.fetch.entropy();if(t===gl.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===gl.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===gl.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===gl.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===gl.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===gl.WorkPackage)return this.fetch.workPackage();if(t===gl.Authorizer)return this.fetch.authorizer();if(t===gl.AuthorizationToken)return this.fetch.authorizationToken();if(t===gl.RefineContext)return this.fetch.refineContext();if(t===gl.AllWorkItems)return this.fetch.allWorkItems();if(t===gl.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===gl.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===gl.AllOperands)return this.fetch.allOperands();if(t===gl.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===gl.AllTransfers)return this.fetch.allTransfers();if(t===gl.OneTransfer){const t=e.get(11);return this.fetch.oneTransfer(t)}return null}}!function(e){e[e.Constants=0]="Constants",e[e.Entropy=1]="Entropy",e[e.AuthorizerTrace=2]="AuthorizerTrace",e[e.OtherWorkItemExtrinsics=3]="OtherWorkItemExtrinsics",e[e.MyExtrinsics=4]="MyExtrinsics",e[e.OtherWorkItemImports=5]="OtherWorkItemImports",e[e.MyImports=6]="MyImports",e[e.WorkPackage=7]="WorkPackage",e[e.Authorizer=8]="Authorizer",e[e.AuthorizationToken=9]="AuthorizationToken",e[e.RefineContext=10]="RefineContext",e[e.AllWorkItems=11]="AllWorkItems",e[e.OneWorkItem=12]="OneWorkItem",e[e.WorkItemPayload=13]="WorkItemPayload",e[e.AllOperands=14]="AllOperands",e[e.OneOperand=15]="OneOperand",e[e.AllTransfers=16]="AllTransfers",e[e.OneTransfer=17]="OneTransfer"}(gl||(gl={}));class pl{currentServiceId;account;index=zn(4);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=ja(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),o=null===n?O.empty():ge.encodeObject(yl,{...n,thresholdBalance:li.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes)});if(r.storeFrom(i,o.raw).isError)return Wn.Panic;null!==n?t.set(7,Qa.OK):t.set(7,Qa.NONE)}}const yl=we.object({codeHash:we.bytes(Re),balance:we.u64,thresholdBalance:we.u64,accumulateMinGas:we.u64.convert(e=>e,yr),onTransferMinGas:we.u64.convert(e=>e,yr),storageUtilisationBytes:we.u64,storageUtilisationCount:we.u32},"ServiceAccountInfoWithThresholdBalance"),ml=Gs.new(void 0,"host-calls"),bl=new TextDecoder("utf8");class Al{currentServiceId;index=zn(100);gasCost=co(0);constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=t.get(11),c=new Uint8Array(Wa(n)),l=new Uint8Array(Wa(a));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,o),ml.trace(`[${this.currentServiceId}] [${s}] ${bl.decode(c)} ${bl.decode(l)}`),Promise.resolve(void 0)}}class Il{currentServiceId;account;index=zn(1);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=ja(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=U.zero(Re);if(r.loadInto(o.raw,i).isError)return Wn.Panic;const a=this.account.lookup(s,o),c=te(null===a?0:a.raw.length),l=t.get(10),h=t.get(11),u=oe(l,c),d=oe(h,te(c-u)),g=null===a?new Uint8Array(0):a.raw.subarray(Number(u),Number(u+d));if(r.storeFrom(n,g).isError)return Wn.Panic;null!==a?t.set(7,c):t.set(7,Qa.NONE)}}class vl{currentServiceId;account;index=zn(2);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=ja(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=t.get(10),a=Wa(n),c=new Uint8Array(4+a);if(null!==s&&za(s,c),r.loadInto(c.subarray(4),i).isError)return Wn.Panic;const l=He(c),h=this.account.read(s,l),u=te(null===h?0:h.raw.length),d=t.get(11),g=t.get(12),f=oe(d,u),p=oe(g,te(u-f)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(f),Number(f+p));if(r.storeFrom(o,y).isError)return Wn.Panic;null!==h?t.set(7,u):t.set(7,Qa.NONE)}}class wl{currentServiceId;account;index=zn(3);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=Wa(i),c=new Uint8Array(4+a);if(za(this.currentServiceId,c),r.loadInto(c.subarray(4),s).isError)return Wn.Panic;const l=He(c),h=Wa(o),u=new Uint8Array(h);if(r.loadInto(u,n).isError)return Wn.Panic;const d=0n===o?null:O.blobFrom(u);if(this.account.write(l,d).isError)return void t.set(7,Qa.FULL);const g=this.account.readSnapshotLength(l);t.set(7,null===g?Qa.NONE:te(g))}}const Sl=[class{currentServiceId;partialState;index=zn(5);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=qa(t.get(8)),n=qa(t.get(9)),o=t.get(10),a=t.get(11),c=new Array,l=new Uint8Array(he(al.sizeHint)),h=ae.fromBlob(l);let u=o;for(let e=0n;e<a;e+=1n){if(h.resetTo(0),r.loadInto(l,u).isError)return Wn.Panic;const{serviceId:e,gas:t}=h.object(al);c.push([e,t]),u=te(u+te(h.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,i,n,c),t.set(7,Qa.OK)):t.set(7,Qa.WHO)}},class{currentServiceId;partialState;chainSpec;index=zn(6);gasCost=co(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=new Uint8Array(2560);if(r.loadInto(n,i).isError)return Wn.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,Qa.CORE);const o=ae.fromBlob(n).sequenceFixLen(we.bytes(Re),80),a=ht.new(o,80);t.set(7,Qa.OK),this.partialState.updateAuthorizationQueue(mr(Number(s)),a)}},class{currentServiceId;partialState;chainSpec;index=zn(7);gasCost=co(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=new Uint8Array(ll*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return Wn.Panic;const n=ae.fromBlob(i).sequenceFixLen(ii.Codec,this.chainSpec.validatorsCount);t.set(7,Qa.OK),this.partialState.updateValidatorsData(Ar(n,this.chainSpec))}},class{currentServiceId;partialState;index=zn(8);gasCost=co(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new cl(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=zn(9);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=yr(t.get(9)),o=yr(t.get(10)),a=U.zero(Re);if(r.loadInto(a.raw,s).isError)return Wn.Panic;const c=this.partialState.newService(a.asOpaque(),i,n,o);c.isOk?t.set(7,te(c.ok)):t.set(7,Qa.CASH)}},class{currentServiceId;partialState;index=zn(10);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=U.zero(Re);if(r.loadInto(o.raw,s).isError)return Wn.Panic;this.partialState.upgradeService(o.asOpaque(),i,n),t.set(7,Qa.OK)}},class{currentServiceId;partialState;index=zn(11);gasCost=e=>{const t=10n+e.get(9);return ho(t)};constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=t.get(8),n=yr(t.get(9)),o=t.get(10),a=U.zero(128);if(r.loadInto(a.raw,o).isError)return Wn.Panic;const c=this.partialState.transfer(s,i,n,a);if(c.isOk)return void t.set(7,Qa.OK);const l=c.error;l!==Wc.DestinationNotFound?l!==Wc.GasTooLow?l!==Wc.BalanceBelowThreshold?b(l):t.set(7,Qa.CASH):t.set(7,Qa.LOW):t.set(7,Qa.WHO)}},class{currentServiceId;partialState;index=zn(12);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=t.get(8),n=U.zero(Re).asOpaque();if(r.loadInto(n.raw,i).isError)return Wn.Panic;if(s===this.currentServiceId)return void t.set(7,Qa.WHO);const o=this.partialState.eject(s,n);if(o.isOk)return void t.set(7,Qa.OK);const a=o.error;a===Jc.InvalidService?t.set(7,Qa.WHO):a===Jc.InvalidPreimage?t.set(7,Qa.HUH):b(a)}},class{currentServiceId;partialState;index=zn(13);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=U.zero(Re);if(r.loadInto(n.raw,s).isError)return Wn.Panic;const o=this.partialState.checkPreimageStatus(n.asOpaque(),i),a=te(0n);if(null===o)return t.set(7,Qa.NONE),void t.set(8,a);switch(o.status){case qc.Requested:return t.set(7,a),void t.set(8,a);case qc.Available:return t.set(7,te(1n+(BigInt(o.data[0])<<32n))),void t.set(8,a);case qc.Unavailable:return t.set(7,te(2n+(BigInt(o.data[0])<<32n))),void t.set(8,te(o.data[1]));case qc.Reavailable:return t.set(7,te(3n+(BigInt(o.data[0])<<32n))),void t.set(8,te((BigInt(o.data[2])<<32n)+BigInt(o.data[1])))}}},class{currentServiceId;partialState;index=zn(14);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=U.zero(Re);if(r.loadInto(n.raw,s).isError)return Wn.Panic;const o=this.partialState.requestPreimage(n.asOpaque(),i);if(o.isOk)return void t.set(7,Qa.OK);const a=o.error;a!==zc.AlreadyAvailable&&a!==zc.AlreadyRequested?a!==zc.InsufficientFunds?b(a):t.set(7,Qa.FULL):t.set(7,Qa.HUH)}},class{currentServiceId;partialState;index=zn(15);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=U.zero(Re);if(r.loadInto(n.raw,s).isError)return Wn.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,Qa.OK):t.set(7,Qa.HUH)}},class{currentServiceId;partialState;index=zn(16);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=U.zero(Re);if(r.loadInto(i.raw,s).isError)return Wn.Panic;this.partialState.yield(i),t.set(7,Qa.OK)}},class{currentServiceId;partialState;index=zn(27);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=ja(7,t,this.currentServiceId),i=t.get(8),n=Wa(t.get(9)),o=O.blobFrom(new Uint8Array(n));if(r.loadInto(o.raw,i).isError)return Wn.Panic;const a=this.partialState.providePreimage(s,o);if(a.isOk)return void t.set(7,Qa.OK);const c=a.error;c!==Yc.ServiceNotFound?c!==Yc.WasNotRequested&&c!==Yc.AlreadyProvided?b(c):t.set(7,Qa.HUH):t.set(7,Qa.WHO)}}];var El;!function(e){e.IS_AUTHORIZED=hl(0),e.REFINE=hl(0),e.ACCUMULATE=hl(5),e.ON_TRANSFER=hl(10)}(El||(El={}));class Cl{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new Va(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new Ya(...t),this.pvm=new Ka(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=Sl.map(s=>new s(e,t.partialState,r)),i=[new Al(e),new cl(e),new vl(e,t.serviceExternalities),new wl(e,t.serviceExternalities),new fl(e,t.fetchExternalities),new Il(e,t.serviceExternalities),new pl(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new Al(e),new cl(e),new vl(e,t.partialState),new wl(e,t.partialState),new Il(e,t.partialState),new pl(e,t.partialState)]}async run(e,t){const r=lc.fromSpi(this.serviceCode.raw,e.raw,!0);return this.pvm.runProgram(r.code,Number(this.entrypoint),t,r.registers,r.memory)}static createAccumulateExecutor(e,t,r,s){const i=Cl.prepareAccumulateHostCalls(e,r,s);return new Cl(t,i,El.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=Cl.prepareOnTransferHostCalls(e,r);return new Cl(t,s,El.ON_TRANSFER)}}const kl=we.object({timeslot:we.u32.asOpaque(),serviceId:we.u32.asOpaque(),transfers:we.sequenceVarLen(tl.Codec)});var xl;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(xl||(xl={}));const Bl=Gs.new(void 0,"deferred-transfers");class _l{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getPotentiallyUpdatedServiceInfo(e,t,r){if(r.includes(e))return null;const s=t.find(t=>t.serviceId===e);return void 0!==s?s.action.account:this.state.getService(e)?.getInfo()??null}getPotentiallyUpdatedPreimage(e,t,r){const s=e.findLast(e=>e.serviceId===t&&e.hash.isEqualTo(r));if(void 0===s)return this.state.getService(t)?.getPreimage(r)??null;switch(s.action.kind){case fi.Provide:return s.action.preimage.blob;case fi.Remove:return null;case fi.UpdateOrAdd:return this.state.getService(t)?.getPreimage(r)??null}}async transition({pendingTransfers:e,timeslot:t,servicesUpdates:r,servicesRemoved:s,preimages:i}){const n=new Map,o=[...r],a=function(e){const t=new Set;for(const r of e)t.add(r);return Array.from(t)}(e.flatMap(e=>[e.source,e.destination]));for(const r of a){const a=e.filter(e=>e.destination===r),c=this.getPotentiallyUpdatedServiceInfo(r,o,s);if(null===c)return _.error(xl.ServiceInfoNotExist);const l=c.codeHash,h=this.getPotentiallyUpdatedPreimage(i,r,l.asOpaque()),u=o.findIndex(e=>e.serviceId===r),d=se(c.balance,...a.map(e=>e.amount));if(d.overflow)return _.error(xl.ServiceBalanceOverflow);const g=li.create({...c,balance:d.value}),f=bi.update({serviceId:r,serviceInfo:g});if(u<0||o[u].action.kind===pi.Create?o.push(f):o[u]=f,null===h||0===a.length){Bl.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`),n.set(r,{count:X(a.length),gasUsed:yr(0)});continue}const p=new sl(this.chainSpec,this.state,r,r,t),y=Cl.createOnTransferExecutor(r,h,{partialState:p}),m=ge.encodeObject(kl,{timeslot:t,serviceId:r,transfers:a},this.chainSpec),b=a.reduce((e,t)=>e+t.gas,0n),{consumedGas:A}=await y.run(m,ho(b));n.set(r,{count:X(a.length),gasUsed:yr(A)})}return _.ok({servicesUpdates:o,transferStatistics:n})}}class Rl extends w{static Codec=we.Class(Rl,{hash:we.bytes(Re).asOpaque(),exportsRoot:we.bytes(Re).asOpaque(),authorizerHash:we.bytes(Re).asOpaque(),payloadHash:we.bytes(Re),gas:we.varU64.asOpaque(),result:Tr.Codec,authorizationOutput:we.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:o}){return new Rl({gas:yr(s),payloadHash:n.asOpaque(),result:o,authorizationOutput:O.blobFrom(e.raw),exportsRoot:r.asOpaque(),hash:i.asOpaque(),authorizerHash:t.asOpaque()})}constructor(e){super(),this.gas=e.gas,this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Rl(e)}}class Ol{static Codec=we.Class(Ol,{hash:we.bytes(Re).asOpaque(),exportsRoot:we.bytes(Re).asOpaque(),authorizerHash:we.bytes(Re).asOpaque(),authorizationOutput:we.blob,payloadHash:we.bytes(Re),result:Tr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new Ol({payloadHash:i,result:n,authorizationOutput:e,exportsRoot:r,hash:s,authorizerHash:t})}constructor(e){this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Ol(e)}}class Ul{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new Ul([],X(0),yr(0n))}}class Tl{reportsDataByServiceId;autoAccumulateServicesByServiceId;serviceIds;constructor(e,t){const{autoAccumulateServicesByServiceId:r,serviceIds:s}=this.transformAutoAccumulateServices(t);this.autoAccumulateServicesByServiceId=r;const{reportsDataByServiceId:i,serviceIds:n}=this.transformReports(e);this.reportsDataByServiceId=i,this.serviceIds=this.mergeServiceIds(n,s)}mergeServiceIds(e,t){const r=new Set;for(const t of e)r.add(t);for(const e of t)r.add(e);return Array.from(r)}transformAutoAccumulateServices(e){const t=new Set,r=new Map;for(const s of e)r.set(s.service,s),t.add(s.service);return{autoAccumulateServicesByServiceId:r,serviceIds:t}}transformReports(e){const t=new Map,r=new Set;for(const s of e)for(const e of s.results){const i=e.serviceId;r.add(i);const n=t.get(i)??Ul.empty();n.reportsLength=X(n.reportsLength+1),n.gasCost=yr(n.gasCost+e.gas),n.operands.push(Rl.new({gas:e.gas,payloadHash:e.payloadHash,result:e.result,authorizationOutput:s.authorizationOutput,exportsRoot:s.workPackageSpec.exportsRoot,hash:s.workPackageSpec.hash,authorizerHash:s.authorizerHash})),t.set(i,n)}for(const e of r){const r=t.get(e)??null,s=this.autoAccumulateServicesByServiceId.get(e)??null;null!==r&&null!==s&&(r.gasCost=yr(r.gasCost+s.gasLimit))}return{reportsDataByServiceId:t,serviceIds:r}}getOperands(e){return this.reportsDataByServiceId.get(e)?.operands??[]}getReportsLength(e){return this.reportsDataByServiceId.get(e)?.reportsLength??X(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??yr(0n)}getServiceIds(){return this.serviceIds}}class Nl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getWorkReportsToAccumulateImmediately(e){return e.filter(e=>0===e.context.prerequisites.length&&0===e.segmentRootLookup.length)}getWorkReportDependencies(e){return Array.from(ct.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return Dl(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>Ui.create({report:e,dependencies:this.getWorkReportDependencies(e)})),ct.from(t))}enqueueReports(e){const t=[];let r=[...e];for(;r.length>0;){const e=r.filter(({dependencies:e})=>0===e.length).map(({report:e})=>e);if(0===e.length)return t;t.push(...e),r=Dl(r,nl(e))}return t}getQueueFromState(e){const t=e%this.chainSpec.epochLength,r=this.state.accumulationQueue.slice(t),s=this.state.accumulationQueue.slice(0,t);return r.concat(s).flat()}}function Dl(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return Ui.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}var Ml;!function(e){e[e.InvalidAnchor=0]="InvalidAnchor",e[e.InvalidOrder=1]="InvalidOrder",e[e.InvalidSignature=2]="InvalidSignature",e[e.NoReportPending=3]="NoReportPending",e[e.InvalidValidatorIndex=4]="InvalidValidatorIndex"}(Ml||(Ml={}));class Pl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition(e){const t=this.chainSpec.coresCount,r=this.verifySignatures(e.assurances),s=e.assurances.map(e=>e.materialize()),i=ht.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:o,bitfield:a}=r;if(!s.isEqualTo(e.parentHash))return _.error(Ml.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return _.error(Ml.InvalidOrder,`order: expected: ${n+1}, got: ${o}`);n=r.validatorIndex,y(a.bitLength===t,`Invalid bitfield length of ${a.bitLength}`);const c=a.indicesOfSetBits();for(const e of c)i[e]+=1}const o=[],a=[],c=this.chainSpec.validatorsSuperMajority;for(let r=0;r<t;r++){const t=i[r],s=this.state.availabilityAssignment[r],n=null!==s;if(t>0&&!n)return _.error(Ml.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&a.push(r),t>=c&&(o.push(s.workReport.data),a.push(r)))}const l=await r;if(l.isError)return l;const h=this.state.availabilityAssignment.slice();for(const e of a)h[e]=null;return _.ok({availableReports:o,stateUpdate:{availabilityAssignment:h}})}async verifySignatures(e){const t=this.state.currentValidatorData,r=[];for(const s of e){const e=s.view(),i=t[e.validatorIndex.materialize()];if(void 0===i)return _.error(Ml.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:Hl(e.anchor.encoded(),e.bitfield.encoded())})}const s=await ir(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return _.error(Ml.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return _.ok(C)}}const Ll=O.blobFromString("jam_available").raw;function Hl(e,t){return O.blobFromParts(Ll,He(O.blobFromParts(e.raw,t.raw)).raw)}const Kl=O.blobFromString("peak");class Vl{hasher;mountains;static empty(e){return new Vl(e)}static fromPeaks(e,t){return new Vl(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(Ql.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=Ql.fromPeak(e,1);for(;;){const e=this.mountains.pop();if(void 0===e)return void this.mountains.push(t);if(e.size!==t.size)return this.mountains.push(e),void this.mountains.push(t);t=e.mergeWith(this.hasher,t)}}getSuperPeakHash(){if(0===this.mountains.length)return U.zero(Re).asOpaque();const e=this.mountains.slice().reverse(),t=e.length;let r=e[0].peak;for(let s=1;s<t;s++){const t=e[s];r=this.hasher.hashConcatPrepend(Kl,r,t.peak)}return r}getPeaks(){const e=[],t=this.mountains;let r=1,s=t.length-1;for(;s>=0;){const i=t[s];i.size>=r&&i.size<2*r?(e.push(i.peak),s-=1):e.push(null),r<<=1}return{peaks:e}}}class Ql{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new Ql(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new Ql(i,n)}mergeWith(e,t){return Ql.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var Fl;!function(e){e[e.BadCoreIndex=0]="BadCoreIndex",e[e.FutureReportSlot=1]="FutureReportSlot",e[e.ReportEpochBeforeLast=2]="ReportEpochBeforeLast",e[e.InsufficientGuarantees=3]="InsufficientGuarantees",e[e.OutOfOrderGuarantee=4]="OutOfOrderGuarantee",e[e.NotSortedOrUniqueGuarantors=5]="NotSortedOrUniqueGuarantors",e[e.WrongAssignment=6]="WrongAssignment",e[e.CoreEngaged=7]="CoreEngaged",e[e.AnchorNotRecent=8]="AnchorNotRecent",e[e.BadServiceId=9]="BadServiceId",e[e.BadCodeHash=10]="BadCodeHash",e[e.DependencyMissing=11]="DependencyMissing",e[e.DuplicatePackage=12]="DuplicatePackage",e[e.BadStateRoot=13]="BadStateRoot",e[e.BadBeefyMmrRoot=14]="BadBeefyMmrRoot",e[e.CoreUnauthorized=15]="CoreUnauthorized",e[e.BadValidatorIndex=16]="BadValidatorIndex",e[e.WorkReportGasTooHigh=17]="WorkReportGasTooHigh",e[e.ServiceItemGasTooLow=18]="ServiceItemGasTooLow",e[e.TooManyDependencies=19]="TooManyDependencies",e[e.SegmentRootLookupInvalid=20]="SegmentRootLookupInvalid",e[e.BadSignature=21]="BadSignature",e[e.WorkReportTooBig=22]="WorkReportTooBig"}(Fl||(Fl={}));const Gl=we.object({B_I:we.u64,B_L:we.u64,B_S:we.u64,C:we.u16,D:we.u32,E:we.u32,G_A:we.u64,G_I:we.u64,G_R:we.u64,G_T:we.u64,H:we.u16,I:we.u16,J:we.u16,L:we.u32,O:we.u16,P:we.u16,Q:we.u16,R:we.u16,S:we.u16,T:we.u16,U:we.u16,V:we.u16,W_A:we.u16,W_B:we.u32,W_C:we.u32,W_E:we.u32,W_G:we.u32,W_M:we.u32,W_P:we.u32,W_R:we.u32,W_T:we.u32,W_X:we.u32,Y:we.u32}),$l=new Map;class jl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=$l.get(e);if(void 0!==t)return t;const r=ge.encodeObject(Gl,{B_I:te(10n),B_L:te(1n),B_S:te(100n),C:Y(e.coresCount),D:X(e.preimageExpungePeriod),E:X(e.epochLength),G_A:te(zl),G_I:te(5e7),G_R:te(5e9),G_T:te(Wl),H:Y(8),I:Y(_r),J:Y(8),L:X(14400),O:Y(8),P:Y(e.slotDuration),Q:Y(80),R:Y(0),S:Y(1024),T:Y(e.rotationPeriod),U:Y(5),V:Y(0),W_A:Y(e.validatorsCount),W_B:X(13794305),W_C:X(4e6),W_E:X(684),W_G:X(4104),W_M:X(3072),W_P:X(6),W_R:X(49152),W_T:X(128),W_X:X(3072),Y:X(e.contestLength)});return $l.set(e,r),r}(this.chainSpec)}entropy(){return this.entropyHash.asOpaque()}authorizerTrace(){return null}workItemExtrinsic(e,t){return null}workItemImport(e,t){return null}workPackage(){return null}authorizer(){return null}authorizationToken(){return null}refineContext(){return null}allWorkItems(){return null}oneWorkItem(e){return null}workItemPayload(e){return null}allOperands(){return p.is(h.V0_6_4)?ge.encodeObject(we.sequenceVarLen(Ol.Codec),this.operands,this.chainSpec):ge.encodeObject(we.sequenceVarLen(Rl.Codec),this.operands,this.chainSpec)}oneOperand(e){if(e>=2n**32n)return null;const t=this.operands[Number(e)];return void 0===t?null:p.isGreaterOrEqual(h.V0_6_5)?ge.encodeObject(Rl.Codec,t,this.chainSpec):ge.encodeObject(Ol.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}var ql;!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(ql||(ql={}));const zl=10000000n,Wl=3500000000n,Jl=Gs.new(void 0,"accumulate"),Yl=we.object({slot:we.u32.asOpaque(),serviceId:we.u32.asOpaque(),operands:we.sequenceVarLen(Ol.Codec)}),Zl=we.object({slot:we.u32.asOpaque(),serviceId:we.u32.asOpaque(),operands:we.sequenceVarLen(Rl.Codec)}),Xl=we.object({slot:we.varU32.asOpaque(),serviceId:we.varU32.asOpaque(),operands:we.varU32});class eh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}findReportCutoffIndex(e,t){const r=t.length;let s=0n;for(let i=0;i<r;i++){const r=t[i].results.map(e=>e.gas).reduce((e,t)=>e+t,0n);if(s+r>e)return i;s+=r}return r}async pvmAccumulateInvocation(e,t,r,s,i,n){const o=this.state.getService(t);if(null===o)return Jl.log(`Service with id ${t} not found.`),_.error(ql.NoService);const a=o.getInfo().codeHash,c=o.getPreimage(a.asOpaque());if(null===c)return Jl.log(`Code with hash ${a} not found for service ${t}.`),_.error(ql.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=ne(He(ge.encodeObject(ol,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return pr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),u=new sl(this.chainSpec,this.state,t,l,e,n),d={partialState:u,serviceExternalities:u,fetchExternalities:new jl(i,r,this.chainSpec)},g=Cl.createAccumulateExecutor(t,c,d,this.chainSpec);let f=O.empty();f=p.is(h.V0_6_4)?ge.encodeObject(Yl,{slot:e,serviceId:t,operands:r},this.chainSpec):p.is(h.V0_6_5)?ge.encodeObject(Zl,{slot:e,serviceId:t,operands:r},this.chainSpec):ge.encodeObject(Xl,{slot:e,serviceId:t,operands:X(r.length)});const y=await g.run(f,ho(s)),[m,b]=u.getStateUpdates();if(y.hasStatus()){const e=y.status;if(e===jn.OOG||e===jn.PANIC)return _.ok({stateUpdate:b,consumedGas:yr(y.consumedGas)})}if(y.hasMemorySlice()&&y.memorySlice.length===Re){const e=U.fromBlob(y.memorySlice,Re);m.yieldedRoot=e.asOpaque()}return _.ok({stateUpdate:m,consumedGas:yr(y.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){Jl.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const o=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return o.isError?(Jl.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(Jl.trace(`Accumulation successful for ${e}.`),o.ok)}async accumulateSequentially(e,t,r,s,i,n){const o=this.findReportCutoffIndex(e,t);if(0===o)return{accumulatedReports:X(0),gasCost:yr(0),yieldedRoots:[],pendingTransfers:[],stateUpdates:[]};const a=t.slice(0,o),c=this.state.privilegedServices.autoAccumulateServices,l=new Tl(a,c),h=t.slice(o),{gasCost:u,yieldedRoots:d,pendingTransfers:g,stateUpdates:f,...p}=await this.accumulateInParallel(l,r,s,i,n);A(p);const y=this.mergeServiceStateUpdates(f);if(y.isError)throw new Error("we should be returning Result here");const{accumulatedReports:m,gasCost:b,yieldedRoots:I,pendingTransfers:v,stateUpdates:w,...S}=await this.accumulateSequentially(yr(e-u),h,r,s,i,y.ok);return A(S),{accumulatedReports:X(o+m),gasCost:yr(u+b),yieldedRoots:d.concat(I),pendingTransfers:g.concat(v),stateUpdates:f.concat(w)}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds(),o=[];let a=yr(0);const c=[],l=[];for(const h of n){const{consumedGas:n,stateUpdate:u}=await this.accumulateSingleService(h,e.getOperands(h),e.getGasCost(h),t,r,rl.copyFrom(i));a=yr(a+n);const d=s.get(h)??{count:X(0),gasUsed:yr(0)};d.count=X(d.count+e.getReportsLength(h)),d.gasUsed=yr(d.gasUsed+n),s.set(h,d),null!==u&&(o.push([h,u]),l.push(...u.transfers),null!==u.yieldedRoot&&c.push([h,u.yieldedRoot]))}return{stateUpdates:o,pendingTransfers:l,yieldedRoots:c,gasCost:a}}mergeServiceStateUpdates(e){const{authManager:t,manager:r,validatorsManager:s}=this.state.privilegedServices;let i=null;const n=this.state.authQueues.slice();let o=!1,a=null;const c=[];for(const[l,h]of e){if(l===r&&null!==h.privilegedServices){const{manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}=h.privilegedServices;y(null===i,"Only one service can update privileged services!"),i=ri.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s})}if(l===t&&null!==h.authorizationQueues)for(const[e,t]of h.authorizationQueues)n[e]=t,o=!0;l===s&&null!==h.validatorsData&&(y(null===a,"Only one service can update designated validators!"),a=h.validatorsData),c.push(h.services)}const l=c.reduce((e,t)=>(e.servicesRemoved.push(...t.servicesRemoved),e.servicesUpdates.push(...t.servicesUpdates),e.preimages.push(...t.preimages),e.storage.push(...t.storage),e),{servicesRemoved:[],servicesUpdates:[],preimages:[],storage:[]}),h=new Set;for(const e of l.servicesUpdates)if(e.action.kind===pi.Create){if(h.has(e.serviceId))return _.error("duplicate service created",`duplicate service ${e.serviceId} has been created!`);h.add(e.serviceId)}const u=rl.new(l);if(null!==i&&(u.privilegedServices=i),null!==a&&(u.validatorsData=a),o)for(const[e,t]of n.entries())u.authorizationQueues.set(mr(e),t);return _.ok(u)}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=nl(e),o=Array.from(n).sort((e,t)=>ei(e,t).value),a=vr(this.state.recentlyAccumulated.slice(1).concat(ct.from(o)),this.chainSpec),c=this.state.accumulationQueue.slice();c[i]=Dl(t,n);for(let e=1;e<s;e++)if(e<r-this.state.timeslot)c[(i+s-e)%s]=[];else{const t=(i+s-e)%s;c[t]=Dl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:vr(c,this.chainSpec),timeslot:r}}getGasLimit(){const e=zl*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=yr(Wl>e?Wl:e);return yr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new Nl(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),o=i.getWorkReportsToAccumulateLater(e),a=Dl(i.getQueueFromState(t).concat(o),nl(n)),c=i.enqueueReports(a),l=n.concat(c),h=this.getGasLimit(),{accumulatedReports:u,yieldedRoots:d,gasCost:g,pendingTransfers:f,stateUpdates:p,...y}=await this.accumulateSequentially(h,l,t,r,s,rl.empty());A(y);const m=l.slice(0,u),b=this.getAccumulationStateUpdate(m,o,t),I=this.mergeServiceStateUpdates(p);if(I.isError)return I;const v=await async function(e){const t=await nt.create(),r=(s=t,{hashConcat:(e,t=[])=>ot(s,[e,...t].map(O.blobFrom)).asOpaque()});var s;return function(e,t){return 1===e.length?t.hashConcat(e[0].raw):function e(t,r){if(0===t.length)return U.zero(Re).asOpaque();if(1===t.length)return t[0];const s=Math.ceil(t.length/2),i=t.slice(0,s),n=t.slice(s);return r.hashConcat(O.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>O.blobFromParts([ie(e),t.raw])),r)}(d);return _.ok({root:v,stateUpdate:{...b,...I.ok.services},accumulationStatistics:s,pendingTransfers:f})}}class th{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=mr(0);r<this.chainSpec.coresCount;r++){let s=t[r].slice();const i=this.state.authQueues[r],n=e.used.get(r);for(void 0!==n&&(s=s.filter(e=>!n.delete(e))),s.push(i[e.slot%80]);s.length>8;)s.shift();t[r]=lt(s)}return{authPools:Ws(t,this.chainSpec)}}}class rh{hasher;state;constructor(e,t){this.hasher=e,this.state=t}transition(e){const t=this.state.recentBlocks.slice(),r=t.length>0?t[t.length-1]:null;null!==r&&(r.postStateRoot=e.priorStateRoot);const s=null!==r?Vl.fromPeaks(this.hasher,r.mmr):Vl.empty(this.hasher);return s.append(e.accumulateRoot),t.push({headerHash:e.headerHash,mmr:s.getPeaks(),postStateRoot:U.zero(Re).asOpaque(),reported:e.workPackages}),t.length>8&&t.shift(),{recentBlocks:t}}}function sh(e,t,r){return function(e,t,r){const s=ih(gr(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){y(32===t.length,`Expected entropy of length 32, got ${t.length}`);const r=e.length,s=function(e,t){const r=new Array(t),s=new Uint8Array(36);s.set(e.raw);for(let e=0;e<t;e++){s.set(ie(X(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=ne(He(s).raw.subarray(t,i))>>>0;r[e]=n}return r}(t,e.length),i=new Array(r);let n=r;for(let t=0;t<r;t++){const r=s[t]%n;i[t]=e[r],n--,e[r]=e[n],e.length=n}return i}(Array(r.validatorsCount).fill(0).map((e,t)=>mr(Math.floor(t*r.coresCount/r.validatorsCount))),e),o=s,a=r.coresCount,n.map(e=>(e+o)%a));var n,o,a;return i}(t,r,e)}function ih(e,t){return Math.floor(e/t)}const nh=O.blobFromString("jam_guarantee").raw;function oh(e){return O.blobFromParts(nh,e.raw)}const ah=1e7;class ch{chainSpec;state;mmrHasher;headerChain;constructor(e,t,r,s){this.chainSpec=e,this.state=t,this.mmrHasher=r,this.headerChain=s}async transition(e){const t=function(e,t){const r=t.coresCount;let s=-1;for(const t of e){const e=t.view().report.view().coreIndex.materialize();if(s>=e)return _.error(Fl.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return _.error(Fl.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return _.ok(C)}(e.guarantees,this.chainSpec);if(t.isError)return t;const r=function(e){for(const t of e){const e=t.view().report.view(),r=e.context.view().prerequisites.view().length,s=e.segmentRootLookup.view().length;if(r+s>8)return _.error(Fl.TooManyDependencies,`Report at ${e.coreIndex.materialize()} has too many dependencies. Got ${r} + ${s}, max: 8`);const i=e.authorizationOutput.view().length;let n=0;for(const t of e.results.view())n+=t.view().result.view().okBlob?.raw.length??0;if(i+n>49152)return _.error(Fl.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return _.ok(C)}(e.guarantees);if(r.isError)return r;const s=this.workReportHashes(e.guarantees),i=this.verifyCredentials(e,s);if(i.isError)return i;const n=ir(i.ok),o=this.verifyPostSignatureChecks(e.guarantees);if(o.isError)return o;const a=this.verifyContextualValidity(e);if(a.isError)return a;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const h=this.state.availabilityAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];h[r.coreIndex]=qs.create({workReport:new Oe(i,r),timeout:e.slot}),l+=1}return _.ok({stateUpdate:{availabilityAssignment:Ws(h,this.chainSpec)},reported:a.ok,reporters:dt.fromArray(F,i.ok.map(e=>e.key)).slice()})}workReportHashes(e){const t=[];for(const r of e)t.push(S(He(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let o=0;for(const r of e){const e=r.view(),a=e.report.view().coreIndex.materialize(),c=t[o];o+=1;const l=e.credentials.view();if(l.length<Hr[0]||l.length>Hr[1])return _.error(Fl.InsufficientGuarantees,`Invalid number of credentials. Expected ${Hr}, got ${l.length}`);const h=s(n,e.slot.materialize());if(h.isError)return h;const u=h.ok;let d=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(d>=r)return _.error(Fl.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${d+1}`);d=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return _.error(Fl.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return _.error(Fl.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:oh(c)})}}return _.ok(i)}(e.guarantees,t,e.slot,(e,t)=>this.getGuarantorAssignment(e,t))}verifyPostSignatureChecks(e){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return _.error(Fl.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return _.error(Fl.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${o}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return _.error(Fl.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return _.error(Fl.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const a=se(...e.results.map(e=>e.gas));if(a.overflow||a.value>ah)return _.error(Fl.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${ah}`)}return _.ok(C)}(e,this.state.availabilityAssignment,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=at.new(),o=ct.new(),a=ct.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=Pr.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),o.insertAll(e.report.context.prerequisites),a.insertAll(e.report.segmentRootLookup.map(e=>e.workPackageHash));for(const r of e.report.results){const e=t.getService(r.serviceId);if(null===e)return _.error(Fl.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return _.error(Fl.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return _.error(Fl.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=at.new();for(const e of r.recentBlocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return _.error(Fl.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return _.error(Fl.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=Vl.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return _.error(Fl.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return _.error(Fl.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return _.error(Fl.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return _.ok(C)}(Math.max(0,e.slot-14400),i,t,r,s);if(c.isError)return c;const l=function(e,t){const r=ct.new();for(const e of t.recentBlocks)r.insertAll(Array.from(e.reported.keys()));for(const e of t.recentlyAccumulated)r.insertAll(Array.from(e));for(const e of t.accumulationQueue)r.insertAll(e.map(e=>e.report.workPackageSpec.hash));for(const e of t.availabilityAssignment)null!==e&&r.insert(e.workReport.data.workPackageSpec.hash);const s=r.intersection(e);for(const e of s)return _.error(Fl.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return _.ok(C)}(ct.viewDictionaryKeys(n),t);if(l.isError)return l;const h=at.new();for(const e of t.recentBlocks)for(const t of e.reported.values())h.set(t.workPackageHash,t.segmentTreeRoot);const u=function({currentWorkPackages:e,recentlyReported:t,prerequisiteHashes:r,segmentRootLookupHashes:s}){const i=(r,s=!1)=>{for(const i of r)if(!e.has(i)&&!t.has(i))return _.error(s?Fl.SegmentRootLookupInvalid:Fl.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return _.ok(C)},n=i(r);if(n.isError)return n;const o=i(s,!0);return o.isError?o:_.ok(C)}({currentWorkPackages:n,recentlyReported:h,prerequisiteHashes:o,segmentRootLookupHashes:a});if(u.isError)return u;for(const t of e.guarantees){const e=t.materialize().report;for(const t of e.segmentRootLookup){let e=n.get(t.workPackageHash);if(void 0===e){const r=h.get(t.workPackageHash);e=void 0!==r?Pr.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return _.error(Fl.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return _.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return _.ok(C);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return _.error(Fl.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t){const r=this.chainSpec.epochLength,s=this.chainSpec.rotationPeriod,i=ih(e,s),n=ih(t,s),o=Math.max(0,i-1)*s;if(t>e)return _.error(Fl.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return _.error(Fl.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let a=this.state.entropy[2],c=this.state.currentValidatorData,l=e;i>n&&(l=gr(e-s),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(l,e,r)&&(a=this.state.entropy[3],c=this.state.previousValidatorData));const h=sh(this.chainSpec,a,l);return _.ok((u=c,d=(e,t)=>({core:e,ed25519:t.ed25519}),h.map((e,t)=>d(e,u[t]))));var u,d}}class lh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getStatistics(e){if(Math.floor(this.state.timeslot/this.chainSpec.epochLength)===Math.floor(e/this.chainSpec.epochLength))return this.state.statistics;const t=Ar(Array.from({length:this.chainSpec.validatorsCount},()=>vi.empty()),this.chainSpec);return ki.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return X(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),X(t)}calculateRefineScore(e){const t={gasUsed:0n,imported:0,extrinsicCount:0,extrinsicSize:0,exported:0};for(const r of e)t.gasUsed+=r.load.gasUsed,t.imported+=r.load.importedSegments,t.extrinsicCount+=r.load.extrinsicCount,t.extrinsicSize+=r.load.extrinsicSize,t.exported+=r.load.exportedSegments;return{gasUsed:yr(t.gasUsed),exported:Y(t.exported),imported:Y(t.imported),extrinsicCount:Y(t.extrinsicCount),extrinsicSize:X(t.extrinsicSize)}}calculateProvidedScoreService(e){const t={count:0,size:0};for(const r of e)t.count+=1,t.size+=r.blob.length;return{count:Y(t.count),size:X(t.size)}}collectServiceIds(e,t,r,s){const i=new Set;for(const t of e)i.add(t.requester);for(const e of t)i.add(e.serviceId);for(const e of r)i.add(e);for(const e of s)i.add(e);return i}transition(e){const{slot:t,authorIndex:r,extrinsic:s,incomingReports:i,availableReports:n}=e,o=this.getStatistics(t),{current:a,cores:c,services:l}=o;y(void 0!==a[r],"authorIndex is out of bounds");const h=a[r].blocks+1;a[r].blocks=X(h);const u=a[r].tickets+s.tickets.length;a[r].tickets=X(u);const d=a[r].preImages+s.preimages.length;a[r].preImages=X(d);const g=s.preimages.reduce((e,t)=>e+t.blob.length,0),f=a[r].preImagesSize+g;a[r].preImagesSize=X(f);for(const{credentials:e}of s.guarantees)for(const{validatorIndex:t}of e){const e=a[t].guarantees+1;a[t].guarantees=X(e)}for(const{validatorIndex:e}of s.assurances){const t=a[e].assurances+1;a[e].assurances=X(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=mr(e),r=i.find(e=>e.coreIndex===t),{imported:o,extrinsicCount:a,extrinsicSize:l,exported:h,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:Y(0),extrinsicCount:Y(0),extrinsicSize:X(0),exported:Y(0),gasUsed:yr(0n)},d=n.find(e=>e.coreIndex===t),g=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=o,c[t].extrinsicCount=a,c[t].extrinsicSize=l,c[t].exports=h,c[t].gasUsed=u,c[t].bundleSize=X(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(d),c[t].popularity=Y(g)}l.clear();const p=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of p){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:o,extrinsicCount:a,extrinsicSize:c,exported:h}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:d,size:g}=this.calculateProvidedScoreService(u),{count:f,gasUsed:p}=e.accumulationStatistics.get(t)??{count:X(0),gasUsed:yr(0n)},{count:y,gasUsed:m}=e.transferStatistics.get(t)??{count:X(0),gasUsed:yr(0n)},b=Ci.empty();b.refinementCount=X(r.length),b.refinementGasUsed=n,b.imports=o,b.extrinsicCount=a,b.extrinsicSize=c,b.exports=h,b.providedCount=d,b.providedSize=g,b.providedCount=d,b.providedSize=g,b.accumulateCount=f,b.accumulateGasUsed=p,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class hh{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var uh;!function(e){e[e.Assurances=0]="Assurances",e[e.Disputes=1]="Disputes",e[e.Safrole=2]="Safrole",e[e.Reports=3]="Reports",e[e.Preimages=4]="Preimages",e[e.SafroleSeal=5]="SafroleSeal",e[e.Accumulate=6]="Accumulate",e[e.DeferredTransfers=7]="DeferredTransfers"}(uh||(uh={}));const dh=(e,t)=>_.taggedError(uh,e,t);class gh{chainSpec;state;hasher;safrole;safroleSeal;disputes;reports;assurances;accumulate;deferredTransfers;preimages;recentHistory;authorization;statistics;constructor(e,t,r,s,{enableParallelSealVerification:i}){this.chainSpec=e,this.state=t,this.hasher=s;const n=Fc.new({synchronous:!i});this.statistics=new lh(e,t),this.safrole=new Zc(e,t,n),this.safroleSeal=new Xc(n),this.recentHistory=new rh(s,t),this.disputes=new xc(e,t),this.reports=new ch(e,t,s,new hh(r)),this.assurances=new Pl(e,t),this.accumulate=new eh(e,t),this.deferredTransfers=new _l(e,t),this.preimages=new pc(t),this.authorization=new th(e,t)}async verifySeal(e,t){const r=this.safrole.getSafroleSealState(e);return await this.safroleSeal.verifyHeaderSeal(t.header.view(),r)}async transition(e,t,r=null,s=!1){const i=e.header.materialize(),n=i.timeSlotIndex;let o=r;if(s&&(o=He(i.seal).asOpaque()),null===o){const t=await this.verifySeal(n,e);if(t.isError)return dh(uh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return dh(uh.Disputes,a);const{disputesRecords:c,availabilityAssignment:l,...h}=a.ok.stateUpdate;A(h);const u=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),knownPackages:[]});if(u.isError)return dh(uh.Reports,u);const{availabilityAssignment:d,...g}=u.ok.stateUpdate;A(g);const f=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(f.isError)return dh(uh.Assurances,f);const{availabilityAssignment:p,...y}=f.ok.stateUpdate;A(y);const m=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize()});if(m.isError)return dh(uh.Safrole,m);const{timeslot:b,ticketsAccumulator:I,sealingKeySeries:v,epochRoot:w,entropy:S,nextValidatorData:E,currentValidatorData:C,previousValidatorData:k,...x}=m.ok.stateUpdate;A(x);const B=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(B.isError)return dh(uh.Preimages,B);const{preimages:R,...O}=B.ok;A(O);const U=await this.accumulate.transition({slot:n,reports:f.ok.availableReports,entropy:S[0]});if(U.isError)return dh(uh.Accumulate,U);const{root:T,stateUpdate:N,accumulationStatistics:D,pendingTransfers:M,...P}=U.ok;A(P);const{privilegedServices:L,authQueues:H,designatedValidatorData:K,timeslot:V,preimages:Q,...F}=N,G=await this.deferredTransfers.transition({pendingTransfers:M,...F,preimages:Q,timeslot:n});if(G.isError)return dh(uh.DeferredTransfers,G);const{servicesUpdates:$,transferStatistics:j,...q}=G.ok;A(q),F.servicesUpdates=$;const z=this.recentHistory.transition({headerHash:t,priorStateRoot:i.priorStateRoot,accumulateRoot:T,workPackages:u.ok.reported}),{recentBlocks:W,...J}=z;A(J);const Y=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:Z,...X}=Y;A(X);const ee=e.extrinsic.materialize(),te=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:ee,incomingReports:ee.guarantees.map(e=>e.report),availableReports:f.ok.availableReports,accumulationStatistics:D,transferStatistics:j}),{statistics:re,...se}=te;return A(se),_.ok({...void 0!==H?{authQueues:H}:{},...void 0!==K?{designatedValidatorData:K}:{},...void 0!==L?{privilegedServices:L}:{},authPools:Z,preimages:R.concat(Q),disputesRecords:c,availabilityAssignment:fh(this.state.availabilityAssignment,d,l,p),recentBlocks:W,statistics:re,timeslot:b,epochRoot:w,entropy:S,currentValidatorData:C,nextValidatorData:E,previousValidatorData:k,sealingKeySeries:v,ticketsAccumulator:I,...F})}getUsedAuthorizerHashes(e){const t=new Map;for(const r of e){const e=r.view().report.view(),s=e.coreIndex.materialize(),i=t.get(s)??ct.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}function fh(e,t,r,s){const i=e.slice();for(const n of t.keys())null!==r[n]&&null!==s[n]||(i[n]=null),null!==t[n]&&e[n]!==t[n]&&(i[n]=t[n]);return i}var ph;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(ph||(ph={}));const yh=(e,t)=>_.taggedError(ph,e,t);class mh{logger;blocks;states;verifier;stf;state;constructor(e,t,r,s,i){this.logger=r,this.blocks=s,this.states=i;const n=this.blocks.getBestHeaderHash(),o=i.getState(n);if(null===o)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new bc(t,s),this.stf=new gh(e,o,s,t,{enableParallelSealVerification:!0}),this.state=o,r.info(`😎 Best time slot: ${o.timeslot} (header hash: ${n})`)}async preverifySeal(e,t){try{const r=await this.stf.verifySeal(e,t);return r.isOk?r.ok:(this.logger.warn(`Unable to pre-verify the seal: ${B(r)}`),null)}catch(e){return this.logger.warn(`Error while trying to pre-verify the seal: ${e}`),null}}async importBlock(e,t,r=!1){const s=this.logger;s.log("🧱 Attempting to import a new block "+(null!==t?"(seal preverified)":""));const i=v("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return yh(ph.Verifier,n);const o=e.header.view().timeSlotIndex.materialize(),a=n.ok;s.log(`🧱 Verified block: Got hash ${a} for block at slot ${o}.`);const c=v("import:stf"),l=await this.stf.transition(e,a,t,r);if(s.log(c()),l.isError)return yh(ph.Stf,l);const h=l.ok,u=v("import:state"),d=await this.states.updateAndSetState(a,this.state,h);if(d.isError)return s.error(`🧱 Unable to update state: ${B(d)}`),yh(ph.Update,d);const g=this.states.getState(a);if(null===g)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(g.backend),s.log(u());const f=v("import:db"),p=this.blocks.insertBlock(new Oe(a,e)),y=await this.states.getStateRoot(g);s.log(`🧱 Storing post-state-root for ${a}: ${y}.`);const m=this.blocks.setPostStateRoot(a,y);return await Promise.all([p,m]),s.log(f()),await this.blocks.setBestHeaderHash(a),_.ok(new Oe(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const bh=Gs.new(void 0,"importer");class Ah extends Un{onBestBlock=new _n;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{bestBlock:e=>this.triggerBestBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}triggerBestBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ae.decodeObject(zr,e,t.chainSpec);this.onBestBlock.emit(r)}}sendBlock(e,t){e.sendSignal("block",t,[t.buffer])}finish(e){return this.onBestBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class Ih extends Un{onBlock=new _n;constructor(){super({name:"ready(importer)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{block:e=>this.triggerOnBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}announce(e,t){const r=this.getConfig(),s=ge.encodeObject(zr,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ae.decodeObject(Zr.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else bh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}async endWork(){return this.onBlock.markDone(),{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const vh=Gs.new(void 0,"importer");if(!$s.isMainThread){Gs.configureAll(process.env.JAM_LOG??"",Ms.LOG);const e=function(){const e=new Dn("ready(importer)",yt.reInit),t=new Ih,r=new Tn;return new Rn("importer",e,[e,t,r])}();kn.receiveChannel(e,$s.parentPort).then(e=>async function(e){vh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{vh.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new mn(r.dbPath),i=new gn(r.chainSpec,s),n=new bn(r.chainSpec,s),o=new mh(r.chainSpec,new fc(r.chainSpec,await wh,new Te),vh,i,n);let a=!1;const c=new yc(r.chainSpec,o);e.onBlock.on(async s=>{const i=c.push(s)??gr(0);if(vh.log(`🧊 Got block: #${i}`),!a){a=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:a}=s,l=v("importBlock"),h=await o.importBlock(i,await n,r.omitSealVerification);if(h.isOk){const r=h.ok;e.announce(t,r),vh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else vh.log(`❌ Rejected block #${a}: ${B(h)}`);vh.log(l())}}finally{a=!1}}})});vh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>vh.error(e))}const wh=nt.create(),Sh=t(import.meta.url)("node:timers/promises");class Eh{chainSpec;keccakHasher;blocks;states;hashAllocator=new Te;lastHeaderHash;lastHeader;lastState;constructor(e,t,r,s){this.chainSpec=e,this.keccakHasher=t,this.blocks=r,this.states=s;const{lastHeaderHash:i,lastHeader:n,lastState:o}=Eh.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=Eh.getLastHeaderAndState(this.blocks,this.states);this.lastHeaderHash=e,this.lastHeader=t,this.lastState=r}static getLastHeaderAndState(e,t){const r=e.getBestHeaderHash(),s=e.getHeader(r)?.materialize()??null,i=t.getState(r);if(null===s)throw new Error(`Missing best header: ${r}! Make sure DB is initialized.`);if(null===i)throw new Error(`Missing last state at ${r}! Make sure DB is initialized.`);return{lastHeaderHash:r,lastHeader:s,lastState:i}}async nextEncodedBlock(){const e=await this.nextBlock();return ge.encodeObject(Zr.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=fr(e%6),r=new fc(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=Yr.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:dr.create({verdicts:[],culprits:[],faults:[]})}),o=ge.encodeObject(Yr.Codec,n,this.chainSpec),a=ae.decodeObject(Yr.Codec.View,o,this.chainSpec),c=r.extrinsic(a).hash,l=ge.create();l.i32(e),l.i16(t),l.bytes(U.fill(90,0));const h=U.fromBlob(l.viewResult().raw,96),u=jr.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:gr(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:U.fill(96,42*e%256).asOpaque(),seal:h.asOpaque()}),d=ge.encodeObject(jr.Codec,u,this.chainSpec),g=ae.decodeObject(jr.Codec.View,d,this.chainSpec);return this.lastHeaderHash=r.header(g).hash,this.lastHeader=u,Zr.create({header:u,extrinsic:n})}}const Ch=Gs.new(void 0,"block-generator");class kh extends Un{onBlock=new _n;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):Ch.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}finish(e){return this.onBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class xh extends Un{constructor(){super({name:"ready(generator)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()}})}sendBlock(e,t){e.sendSignal("block",t.raw,[t.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Config not received.");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const Bh=Gs.new(void 0,"block-generator");if(!$s.isMainThread){Gs.configureAll(process.env.JAM_LOG??"",Ms.LOG);const e=function(){const e=new Dn("ready(generator)",yt.reInit),t=new xh,r=new Tn;return new Rn("block-generator",e,[e,t,r])}();kn.receiveChannel(e,$s.parentPort).then(e=>async function(e){Bh.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new mn(r.dbPath),i=new gn(r.chainSpec,s),n=new bn(r.chainSpec,s),o=await t.doUntil("finished",async(e,t,s)=>{let o=0;const a=new Eh(r.chainSpec,await nt.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();Bh.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,Sh.setTimeout)(3e3)}});Bh.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{Bh.error(e),void 0!==e.stack&&Bh.error(e.stack),void 0!==e.cause&&Bh.error(e.cause)})}const _h=t(import.meta.url)("dgram");var Rh,Oh;(Oh=Rh||(Rh={}))[Oh.NOTSET=0]="NOTSET",Oh[Oh.DEBUG=1]="DEBUG",Oh[Oh.INFO=2]="INFO",Oh[Oh.WARN=3]="WARN",Oh[Oh.ERROR=4]="ERROR",Oh[Oh.SILENT=100]="SILENT";const Uh="captureStackTrace"in Error,Th="stackTraceLimit"in Error;function Nh(e){switch(e){case Rh.NOTSET:return"NOTSET";case Rh.DEBUG:return"DEBUG";case Rh.INFO:return"INFO";case Rh.WARN:return"WARN";case Rh.ERROR:return"ERROR";case Rh.SILENT:return"SILENT"}}function Dh(e,t){return"function"==typeof t?t():t}function Mh(e){return JSON.stringify(e,Dh)}const Ph=Symbol("level"),Lh=Symbol("key"),Hh=Symbol("keys"),Kh=Symbol("date"),Vh=Symbol("msg"),Qh=Symbol("stack"),Fh=Symbol("data"),Gh=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Lh)s+=r.key;else if(n===Hh)s+=r.keys;else if(n===Kh)s+=r.date().toISOString();else if(n===Vh)null!=r.msg&&(s+=r.msg);else if(n===Ph)s+=Nh(r.level);else if(n===Fh)s+=Mh(r.data);else if(n===Qh){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${Ph}:${Lh}:${Vh}`,$h=class{formatter;constructor(e=Gh){this.formatter=e}setFormatter(e){this.formatter=e}handle(e,t){const r=null!=t?t(e):this.format(e);this.emit(r)}format(e){return this.formatter(e)}},jh=class extends $h{emit(e){console.error(e)}};class qh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Rh.NOTSET,r=[new jh],s){this.key=e,this.level=t,this.handlers=new Set(r),this.parent=s,this.keys=null!=s?`${s.keys}.${e}`:e,this.loggersRegistry=new FinalizationRegistry(e=>{this._loggers.delete(e)})}get loggers(){return new Map([...this._loggers.entries()].map(([e,t])=>{const r=t.deref();return null!=r?[e,r]:void 0}).filter(e=>null!=e))}getChild(e){let t=this._loggers.get(e),r=t?.deref();return null!=r||(r=new qh(e,Rh.NOTSET,[],this),t=new WeakRef(r),this._loggers.set(e,t),this.loggersRegistry.register(r,e)),r}getParent(){return this.parent}setLevel(e){this.level=e}getEffectiveLevel(){return this.level!==Rh.NOTSET?this.level:this.parent?this.parent.getEffectiveLevel():this.level}isEnabledFor(e){return e>=this.level}addHandler(e){this.handlers.add(e)}removeHandler(e){this.handlers.delete(e)}clearHandlers(){this.handlers.clear()}hasHandlers(){return!!this.handlers.size||(this.parent?.hasHandlers()??!1)}setFilter(e){this.filter=e}unsetFilter(){delete this.filter}debug(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.DEBUG,t):this.log(e,t,Rh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.INFO,t):this.log(e,t,Rh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.WARN,t):this.log(e,t,Rh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.ERROR,t):this.log(e,t,Rh.ERROR,r)}log(e,t,r,s){if(r<this.getEffectiveLevel())return;const i=this.makeRecord(e,t,r);this.callHandlers(i,r,s)}makeRecord(e,t,r){return{logger:this,key:this.key,keys:this.keys,level:r,msg:e?.toString(),data:t,date:()=>new Date,stack:()=>{let e;if(Uh&&Th){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,qh.prototype.log),Error.stackTraceLimit--,e=t.stack,e=e.slice(e.indexOf("\n",e.indexOf("\n")+1)+1)}else e=(new Error).stack??"",e=e.slice(e.indexOf("\n")+1);return e}}}callHandlers(e,t,r,s=""){if(!(t<this.getEffectiveLevel())&&(s=`${this.key}.${s}`,null==this.filter||this.filter.test(s))){for(const t of this.handlers)t.handle(e,r);this.parent&&this.parent.callHandlers(e,t,r,s)}}}const zh=qh;t(import.meta.url)("node:process");class Wh extends Event{detail;constructorParams;constructor(e=new.target.name,t,r){"string"==typeof e?(super(e,t),this.detail=t?.detail):(super(new.target.name,e),this.detail=e.detail,r=t),this.constructorParams=r??arguments}clone(){try{return new this.constructor(...this.constructorParams)}catch(e){if("TypeError"===e.name)throw new TypeError(`Cloning ${this.constructor.name} requires the original constructor arguments to be passed into super`);throw e}}}const Jh=Wh;class Yh extends Jh{constructor(e){super(Yh.name,e,arguments)}}const Zh=Yh;class Xh extends Jh{constructor(e){super(Xh.name,e,arguments)}}const eu=Xh;class tu extends Jh{constructor(e){super(tu.name,e,arguments)}}const ru=tu,su=Symbol("_eventTarget"),iu=Symbol("eventTarget"),nu=Symbol("_eventHandlers"),ou=Symbol("eventHandlers"),au=Symbol("_eventHandled"),cu=Symbol("eventHandled"),lu=Symbol("_handleEventError"),hu=Symbol("handleEventError");function uu(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function du(e,t){return e.capture===t.capture}function gu(){return e=>{const t=class extends e{[su]=new EventTarget;[nu]=new Map;[au]=new WeakSet;[lu]=e=>{throw e.detail};constructor(...e){super(...e),this[su].addEventListener(ru.name,this[lu])}get[iu](){return this[su]}get[ou](){return this[nu]}get[cu](){return this[au]}get[hu](){return this[lu]}addEventListener(e,t,r){r=uu(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[nu].get(e),void 0===n&&(n=new Set,this[nu].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,du(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[au].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new ru({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new ru({detail:e}))}},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[au].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new ru({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new ru({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[su].addEventListener(e,i,r),e===ru.name&&1===n?.size&&this[su].removeEventListener(ru.name,this[lu])}removeEventListener(e,t,r){let s,i,n;if(r=uu(r),null!=t){if(i=this[nu].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&du(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[su].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===ru.name&&0===i.size&&this[su].addEventListener(ru.name,this[lu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof ru)return this[su].dispatchEvent(e);{let t=this[su].dispatchEvent(e);if(t&&!this[au].has(e)){const r=new Zh({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[su].dispatchEvent(r)}if(t){const r=new eu({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[su].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function fu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return await t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}async function*pu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return yield*t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}class yu extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof yu?e:super.resolve(e)}static reject(e){return super.reject(e)}static all(e,t){const r=super.all(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static allSettled(e,t){const r=super.allSettled(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static race(e,t){const r=super.race(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static any(e,t){const r=super.any(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static from(e,t){return new this((t,r)=>{e.then(t,r)},t)}reject;abortController;constructor(e,t){let r,s,i,n;"function"==typeof t?(r=new AbortController,t(r.signal),s=r.signal,i=!0):null!=t?(r=t,s=t.signal,i=!0):(r=new AbortController,s=new Proxy(r.signal,{get:(e,t,r)=>"addEventListener"===t?function(...r){return i=!0,e[t].apply(this,r)}:Reflect.get(e,t,r),set:(e,t,r)=>("onabort"===t&&(i=!0),Reflect.set(e,t,r)),deleteProperty:(e,t)=>("onabort"===t&&(i=!0),Reflect.deleteProperty(e,t))}),i=!1),super((t,r)=>{n=e=>{e instanceof DOMException&&"AbortError"===e.name&&(e=void 0),r(e)},e(t,n,s)}),i||r.signal.addEventListener("abort",()=>{n(r.signal.reason)},{once:!0}),this.reject=n,this.abortController=r}get[Symbol.toStringTag](){return this.constructor.name}cancel(e){this.abortController.abort(e)}then(e,t,r){let s,i,n;"function"==typeof e&&(i=t=>e(t,s)),"function"==typeof t&&(n=e=>t(e,s));const o=super.then(i,n),a=yu.from(o,r);return s=a.abortController.signal,a}catch(e,t){let r,s;"function"==typeof e&&(s=t=>e(t,r));const i=super.catch(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}finally(e,t){let r,s;"function"==typeof e&&(s=()=>e(r));const i=super.finally(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}}const mu=yu,bu=t(import.meta.url)("node:perf_hooks");var Au,Iu=(Au=function(e,t){return Au=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Au(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Au(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),vu=function(e){function t(t){var r,s,i,n=this.constructor,o=e.call(this,t)||this;return Object.defineProperty(o,"name",{value:n.name,enumerable:!1,configurable:!0}),r=o,s=n.prototype,(i=Object.setPrototypeOf)?i(r,s):r.__proto__=s,function(e,t){void 0===t&&(t=e.constructor);var r=Error.captureStackTrace;r&&r(e,t)}(o),o}return Iu(t,e),t}(Error);const wu=class extends vu{static description="";static fromJSON(e){if("object"!=typeof e||e.type!==this.name||"object"!=typeof e.data||"string"!=typeof e.data.message||isNaN(Date.parse(e.data.timestamp))||"object"!=typeof e.data.data||"stack"in e.data&&"string"!=typeof e.data.stack)throw new TypeError(`Cannot decode JSON to ${this.name}`);const t=new this(e.data.message,{timestamp:new Date(e.data.timestamp),data:e.data.data,cause:e.data.cause});return t.stack=e.data.stack,t}data;cause;timestamp;constructor(e="",t={}){super(e),this.timestamp=t.timestamp??new Date(bu.performance.timeOrigin+bu.performance.now()),this.data=t.data??{},this.cause=t.cause}get description(){return this.constructor.description}toJSON(){return{type:this.constructor.name,description:this.description,data:{message:this.message,timestamp:this.timestamp,data:this.data,cause:this.cause,stack:this.stack}}}};function Su(e,t,r=new Set){if(r.has(e))return!1;if(r.add(e),t(e))return!0;if(e instanceof AggregateError){for(const s of e.errors){const e=Su(s,t,r);if(e)return e}return Su(e.cause,t,r)}return e instanceof Error&&Su(e.cause,t,r)}class Eu extends wu{static description="Timer error"}class Cu extends Eu{static description="The timer has already ended"}class ku{_delay;lazy;timestamp;_scheduled;handler;p;resolveP;rejectP;abortController;timeoutRef;_status=null;constructor(e,t=0,r=!1,s){let i,n;"function"==typeof e?i=e:"object"==typeof e&&null!==e&&(i=e.handler,t=e.delay??t,r=e.lazy??r,s=e.controller??s),isNaN(t)?t=0:(t=Math.max(t,0),isFinite(t)&&(t=Math.min(t,2**31-1))),this.handler=i,this._delay=t,this.lazy=r,"function"==typeof s?(n=new AbortController,s(n.signal)):null!=s?n=s:(n=new AbortController,n.signal.addEventListener("abort",()=>{this.reject(n.signal.reason)})),this.p=new mu((e,t)=>{this.resolveP=e.bind(this.p),this.rejectP=t.bind(this.p)},n),this.abortController=n,isFinite(t)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},t),this.timestamp=new Date(bu.performance.timeOrigin+bu.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(bu.performance.timeOrigin+bu.performance.now()))}get[Symbol.toStringTag](){return this.constructor.name}get status(){return this._status}get scheduled(){return this._scheduled}get delay(){return this._delay}getTimeout(){return null!==this._status?0:null==this._scheduled?1/0:Math.max(Math.trunc(this._scheduled.getTime()-(bu.performance.timeOrigin+bu.performance.now())),0)}toString(){return this.getTimeout().toString()}valueOf(){return this.getTimeout()}cancel(e){this.p.catch(()=>{}),this.p.cancel(e)}then(e,t,r){return this.p.then(e,t,r)}catch(e,t){return this.p.catch(e,t)}finally(e,t){return this.p.finally(e,t)}refresh(){if(null!=this._status)throw new Cu;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Cu;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(bu.performance.timeOrigin+bu.performance.now()+e)):(this.timeoutRef=setInterval(()=>{},2**31-1),delete this._scheduled)}async fulfill(){if(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,null!=this.handler)try{const e=await this.handler(this.abortController.signal);this.resolveP(e)}catch(e){this.rejectP(e)}else this.resolveP();delete this.handler,this._status="settled"}async reject(e){this.lazy&&"settling"===this._status||"settled"===this._status||(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,this.rejectP(e),delete this.handler,this._status="settled")}}const xu=ku;function Bu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function _u(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new xu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof xu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new xu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new mu((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}class Ru extends wu{static description="Async locks error"}class Ou extends Ru{static description="Async locks timeout"}const Uu=class{limit;priority;_count=0;currentWeight=0;queue=[];abortQueueMap=new WeakMap;constructor(e,t=!1){if(e<1)throw new RangeError("Semaphore must be constructed with `limit` >= 1");this.limit=e,this.priority=t}get count(){return this._count}isLocked(){return this._count>0}lock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},()=>_u((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=Bu();if(e.signal.aborted)return this._count--,i(e.signal.reason),r;const n=()=>{this._count--;const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)};let o=!1;const a={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{o||(o=!0,this._count--,this.currentWeight-=t,this.processQueue())},this])},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,Ou,r,[t])}waitForUnlock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},_u((e,t)=>{const{p:r,resolveP:s,rejectP:i}=Bu();if(e.signal.aborted)return i(e.signal.reason),r;const n=()=>{const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)},o={task:()=>{e.signal.removeEventListener("abort",n),s()},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,Ou,r,[t])}withF(...e){const t=e.pop();return fu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return pu([this.lock(...e)],([e])=>t(e))}insertQueue(e){if(this.priority){let t=this.queue.length;for(;t>0&&this.queue[t-1].weight<e.weight;)t--;this.queue.splice(t,0,e)}else this.queue.unshift(e)}processQueue(){for(;this.queue.length>0&&this.currentWeight+this.queue[this.queue.length-1].weight<=this.limit;){const e=this.queue.pop();e.aborted||e.task()}}},Tu=class{semaphore=new Uu(1);get count(){return this.semaphore.count}isLocked(){return this.semaphore.isLocked()}lock(e){const t=this.semaphore.lock(1,e);return()=>{const e=t();return e.then(([e])=>[e,this],void 0,t=>{t.addEventListener("abort",()=>{e.cancel(t.reason)},{once:!0})})}}waitForUnlock(e){return this.semaphore.waitForUnlock(1,e)}withF(...e){const t=e.pop();return fu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return pu([this.lock(...e)],([e])=>t(e))}},Nu=class{readersLock=new Tu;writersLock=new Tu;readersRelease;readerCountBlocked=0;acquireReadersLockP;_readerCount=0;_writerCount=0;get count(){return this.readerCount+this.writerCount}get readerCount(){return this._readerCount+this.readerCountBlocked}get writerCount(){return this._writerCount}isLocked(e){return"read"===e?0===this._writerCount&&this.readersLock.isLocked():"write"===e?this.writersLock.isLocked():this.readersLock.isLocked()||this.writersLock.isLocked()}lock(...e){const t=(2===e.length||"string"==typeof e[0]?e[0]:void 0)??"write",r=2===e.length?e[1]:"string"!=typeof e[0]?e[0]:void 0;switch(t){case"read":return this.read(r);case"write":return this.write(r)}}read(e){return e=null!=e?{...e}:{},()=>_u(async e=>{if(this._writerCount>0){++this.readerCountBlocked;const t=this.writersLock.waitForUnlock(e);try{await t}finally{--this.readerCountBlocked}}if(1===++this._readerCount){const t=this.readersLock.lock(e);this.acquireReadersLockP=t();try{[this.readersRelease]=await this.acquireReadersLockP}catch(e){throw--this._readerCount,e}}else await this.acquireReadersLockP.catch(()=>{});let t=!1;return[async()=>{t||(t=!0,0===--this._readerCount&&await this.readersRelease())},this]},!0,1/0,Ou,e,[])}write(e){return e=null!=e?{...e}:{},()=>_u(async e=>{++this._writerCount;const t=this.writersLock.lock(e)();let r;try{[r]=await t}catch(e){throw--this._writerCount,e}const s=this.readersLock.lock(e)();try{[this.readersRelease]=await s}catch(e){throw await r(),--this._writerCount,e}let i=!1;return[async()=>{i||(i=!0,await this.readersRelease(),await r(),--this._writerCount)},this]},!0,1/0,Ou,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return mu.all([t,r]).then(()=>{},void 0,e=>{e.addEventListener("abort",()=>{t.cancel(e.reason),r.cancel(e.reason)},{once:!0})})}withF(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadF(...e);case"write":return this.withWriteF(...e)}}withReadF(...e){const t=e.pop();return fu([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return fu([this.write(...e)],([e])=>t(e))}withG(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadG(...e);case"write":return this.withWriteG(...e)}}withReadG(...e){const t=e.pop();return pu([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return pu([this.write(...e)],([e])=>t(e))}},Du=Symbol("_running"),Mu=Symbol("running"),Pu=Symbol("_destroyed"),Lu=Symbol("destroyed"),Hu=Symbol("_status"),Ku=Symbol("status"),Vu=Symbol("_statusP"),Qu=Symbol("statusP"),Fu=Symbol("resolveStatusP"),Gu=Symbol("initLock"),$u=(async()=>{}).constructor,ju=function*(){}.constructor,qu=async function*(){}.constructor,zu="captureStackTrace"in Error;function Wu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ju(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);zu?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Yu extends Jh{}class Zu extends Yu{}class Xu extends Yu{}class ed extends Yu{}class td extends Yu{}class rd extends Yu{}class sd extends Yu{}class id extends wu{static description="Async init error"}class nd extends id{static description="Async init is not running"}class od extends id{static description="Async init is destroyed"}function ad({eventDestroy:e=rd,eventDestroyed:t=sd}={}){return r=>{const{p:s,resolveP:i}=Wu(),n=class extends(gu()(r)){[Pu]=!1;[Hu]=null;[Vu]=s;[Fu]=i;[Gu]=new Nu;get[Lu](){return this[Pu]}get[Ku](){return this[Hu]}get[Qu](){return this[Vu]}async destroy(...r){return this[Gu].withWriteF(async()=>{if(this[Pu])return;this[Hu]="destroying",this[Fu]("destroying");const{p:s,resolveP:i}=Wu();let n;return this[Vu]=s,this[Fu]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[Pu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Vu]=e,this[Fu]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function cd(e=new od,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof $u?async function(...s){if(this[Gu].isLocked("write")&&null===this[Hu]&&await this[Vu],r.includes(this[Hu]))return a.apply(this,s);if(t)return this[Gu].withReadF(async()=>{if(this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)}:a instanceof ju?function*(...t){if(r.includes(this[Hu]))return yield*a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Ku]||this[Pu])throw Ju(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof qu?async function*(...s){if(this[Gu].isLocked("write")&&null===this[Hu]&&await this[Vu],r.includes(this[Hu]))return yield*a.apply(this,s);if(t)return yield*this[Gu].withReadG(()=>{if(this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||this[Pu])throw Ju(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Hu]))return a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Ku]||this[Pu])throw Ju(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function ld({eventStart:e=Zu,eventStarted:t=Xu,eventStop:r=ed,eventStopped:s=td}={}){return i=>{const{p:n,resolveP:o}=Wu(),a=class extends(gu()(i)){[Du]=!1;[Hu]=null;[Vu]=n;[Fu]=o;[Gu]=new Nu;get[Mu](){return this[Du]}get[Ku](){return this[Hu]}get[Qu](){return this[Vu]}async start(...r){return this[Gu].withWriteF(async()=>{if(this[Du])return;this[Hu]="starting",this[Fu]("starting");const{p:s,resolveP:i}=Wu();let n;return this[Vu]=s,this[Fu]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[Du]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Vu]=e,this[Fu]=t})}async stop(...e){return this[Gu].withWriteF(async()=>{if(!this[Du])return;this[Hu]="stopping",this[Fu]("stopping");const{p:t,resolveP:i}=Wu();let n;return this[Vu]=t,this[Fu]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[Du]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Vu]=e,this[Fu]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function hd(e=new nd,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof $u?async function(...s){if(this[Gu].isLocked("write")&&null===this[Hu]&&await this[Vu],r.includes(this[Hu]))return a.apply(this,s);if(t)return this[Gu].withReadF(async()=>{if(!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)}:a instanceof ju?function*(...t){if(r.includes(this[Hu]))return yield*a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Ku]||!this[Du])throw Ju(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof qu?async function*(...s){if(this[Gu].isLocked("write")&&null===this[Hu]&&await this[Vu],r.includes(this[Hu]))return yield*a.apply(this,s);if(t)return yield*this[Gu].withReadG(()=>{if(!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||!this[Du])throw Ju(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Hu]))return a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Ku]||!this[Du])throw Ju(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class ud extends Uint8Array{string;static fromString(e){const t=Buffer.from(e,"hex");return new this(t.buffer,t.byteOffset,t.byteLength)}static fromBuffer(e){return new this(e.buffer,e.byteOffset,e.byteLength)}constructor(...e){super(...e),this.string=this.toBuffer().toString("hex")}toString(){return this.string}toBuffer(){return Buffer.from(this.buffer,this.byteOffset,this.byteLength)}[Symbol.toPrimitive](e){return this.toString()}}const dd=ud;class gd{[Symbol.toStringTag]="QUICConnectionMap";_serverConnections=new Map;_clientConnections=new Map;constructor(e){if(null!=e)for(const[t,r]of e)this.set(t,r)}get size(){return this._serverConnections.size+this._clientConnections.size}get serverConnections(){return this._serverConnections}get clientConnections(){return this._clientConnections}has(e){return this._serverConnections.has(e.toString())||this._clientConnections.has(e.toString())}get(e){return this._serverConnections.get(e.toString())??this._clientConnections.get(e.toString())}set(e,t){return"server"===t.type?this._serverConnections.set(e.toString(),t):"client"===t.type&&this._clientConnections.set(e.toString(),t),this}delete(e){return this._serverConnections.delete(e.toString())||this._clientConnections.delete(e.toString())}clear(){this._serverConnections.clear(),this._clientConnections.clear()}forEach(e,t){this._serverConnections.forEach((r,s)=>{e.bind(t)(r,dd.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,dd.fromString(s),this)})}[Symbol.iterator](){const e=this._serverConnections[Symbol.iterator](),t=this._clientConnections[Symbol.iterator](),r={next:()=>{const r=e.next();if(!r.done){const[e,t]=r.value;return{done:!1,value:[dd.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[dd.fromString(e),t]}}return{done:!0,value:void 0}},[Symbol.iterator]:()=>r};return r}entries(){return this[Symbol.iterator]()}keys(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[0]}},[Symbol.iterator]:()=>e};return e}values(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[1]}},[Symbol.iterator]:()=>e};return e}}const fd=gd,pd="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",yd=t(import.meta.url)("dns");var md=o(618);class bd extends wu{static description="QUIC error"}class Ad extends wu{static description="You should never see this error"}class Id extends wu{static description="Host provided was not valid"}class vd extends wu{static description="Port provided was not valid"}class wd extends bd{static description="QUIC config error"}class Sd extends bd{static description="QUIC Socket error"}class Ed extends Sd{static description="QUIC Socket is not running"}class Cd extends Sd{static description="QUIC Socket has active connections"}class kd extends Sd{static description="QUIC Socket cannot bind to the specified address"}class xd extends Sd{static description="QUIC Socket cannot send to the specified address"}class Bd extends Sd{static description="QUIC Socket internal error"}class _d extends bd{static description="QUIC Client error"}class Rd extends _d{static description="QUIC Client is destroyed"}class Od extends _d{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Ud extends _d{static description="QUIC Client had a failure relating to an invalid argument"}class Td extends _d{static description="QUIC Client cannot be created with the specified host"}class Nd extends _d{static description="QUIC Client internal error"}class Dd extends bd{static description="QUIC Server error"}class Md extends Dd{static description="QUIC Server is not running"}class Pd extends Dd{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class Ld extends Dd{static description="QUIC Server creating a new connection"}class Hd extends Dd{static description="QUIC Server internal error"}class Kd extends Dd{static description="QUIC Server is stopping"}class Vd extends bd{static description="QUIC Connection error"}class Qd extends Vd{static description="QUIC Connection is stopping"}class Fd extends Vd{static description="QUIC Connection is not running"}class Gd extends Vd{static description="QUIC Connection cannot be restarted because it has already been closed"}class $d extends bd{static description="QUIC Connection start requires data when it is a server connection"}class jd extends Vd{static description="QUIC connection invalid configuration"}class qd extends Vd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class zd extends qd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Wd extends Vd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class Jd extends qd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Yd extends Vd{static description="QUIC Connection max idle timeout exhausted"}class Zd extends Vd{static description="QUIC Connection internal error"}class Xd extends bd{static description="QUIC Stream error"}class eg extends Xd{static description="QUIC Stream is destroyed"}class tg extends Xd{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class rg extends Xd{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class sg extends Xd{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class ig extends Xd{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class ng extends Xd{static description="QUIC Stream internal error"}class og extends Xd{static description="QUIC Stream limit has been reached"}const ag=new TextEncoder,cg=new TextDecoder("utf-8");function lg(e){throw new Ad(e)}function hg(e){return function(...t){return new Promise((r,s)=>{t.push((e,...t)=>{if(null!=e)return s(e);0===t.length?r():1===t.length?r(t[0]):r(t)}),e.apply(this,t)})}}function ug(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function dg(e){const[t]=md.Validator.isValidIPv4String(e);return t}function gg(e){const[t]=md.Validator.isValidIPv6String(e);return!!t||fg(e)}function fg(e){if(e.startsWith("::ffff:"))try{return md.IPv6.fromString(e),!0}catch{if(dg(e.slice(7)))return!0}return!1}function pg(e){if(!dg(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function yg(e){const t=e.slice(7);if(dg(t))return t;const r=t.match(/^([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/);if(null==r)throw new TypeError("Invalid IPv4 mapped IPv6 address");return(r[1].padStart(4,"0")+r[2].padStart(4,"0")).match(/.{1,2}/g).map(e=>parseInt(e,16)).join(".")}function mg(e){const t=new md.IPv4("0.0.0.0"),r=new md.IPv6("::");if(fg(e)){const r=yg(e);return new md.IPv4(r).isEquals(t)?pg("127.0.0.1"):e}return dg(e)&&new md.IPv4(e).isEquals(t)?"127.0.0.1":gg(e)&&new md.IPv6(e).isEquals(r)?"::1":e}async function bg(e){return(await yd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Ag(e,t){if(dg(e))return[e,"udp4"];if(gg(e))return[e,"udp6"];try{return Ag(e=await t(e),t)}catch{throw new Id}}function Ig(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new vd;return e}function vg(e,t=0){let r;return r=dg(e)?`${e}:${t}`:gg(e)?`[${e}]:${t}`:`${e}:${t}`,r}function wg(e,t,r,s,i){if("0.0.0.0"===(n=r)||"::"===n||"::0"===n||"::ffff:0.0.0.0"===n||"::ffff:0:0"===n)throw new i(`Invalid wildcard target host ${r}`);var n;const o=fg(e),a=fg(r);if("ipv4&ipv6"===t&&"udp4"===s)return pg(r);if("ipv4"===t){if(o){if("udp4"===s)return pg(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return yg(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||a)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function Sg(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(cg.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(cg.decode(r).trim()+"\n");return t}function Eg(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function Cg(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function kg(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function xg(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Bg(e,t=1e5){An.setMaxListeners(t,e)}class _g extends Jh{}class Rg extends _g{}class Og extends Rg{}class Ug extends Rg{}class Tg extends Rg{}class Ng extends _g{}class Dg extends Ng{}class Mg extends Rg{}class Pg extends Ng{}class Lg extends _g{}class Hg extends Lg{}class Kg extends Lg{}class Vg extends Lg{}class Qg extends _g{}class Fg extends Qg{}class Gg extends Qg{}class $g extends Qg{}class jg extends Qg{}class qg extends Qg{}class zg extends _g{}class Wg extends zg{}class Jg extends zg{}class Yg extends zg{}class Zg extends zg{}class Xg extends zg{}var ef=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let tf=class{connectionMap=new fd;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(Cg(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[Mu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=pd.Header.fromSlice(e,pd.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new dd(r.dcid),i={host:t.address,port:t.port},n=this.connectionMap.get(s);if(null!=n)await n.recv(e,i);else{if(null==this.server)return;try{await this.server.acceptConnection(i,r,s,e)}catch(e){if(Su(e,e=>e instanceof Sd)){const t=new Bd("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new Ug({detail:t})),void this.dispatchEvent(new Tg)}if(e instanceof Ld)return;throw e}}};constructor({resolveHostname:e=bg,logger:t}){this.logger=t??new zh(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=ug();this._closedP=r,this.resolveClosedP=s}get host(){return this._host}get port(){return this._port}get type(){return this._type}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r=!1,ipv6Only:s=!1}={}){Bg(this[su]);let i=vg(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await Ag(e,this.resolveHostname),a=Ig(t);this.socket=_h.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=hg(this.socket.bind).bind(this.socket),this.socketClose=hg(this.socket.close).bind(this.socket),this.socketSend=hg(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=ug();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new kd(e!==n?`Could not bind to resolved ${e} -> ${n}`:`Could not bind to ${e}`,{cause:t})}this.socket.removeListener("error",l);const u=this.socket.address();this._host=u.address,this._port=u.port,"::"!==n||s?"udp4"===o||fg(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(Ug.name,this.handleEventQUICSocketError),this.addEventListener(Tg.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=vg(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=vg(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Cd(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new Tg),await this._closedP;const{p:r,resolveP:s}=ug();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(Ug.name,this.handleEventQUICSocketError),this.removeEventListener(Tg.name,this.handleEventQUICSocketClose),this.socket.off("message",this.handleSocketMessage),this.logger.info(`Stopped ${this.constructor.name} on ${t}`)}async send(...e){let t;if(3===e.length&&"string"==typeof e[2])t=2;else{if(5!==e.length||"string"!=typeof e[4])throw new TypeError("QUICSocket.send requires `port` and `address` parameters");t=4}const r=e[t];let[s,i]=await Ag(r,this.resolveHostname);return s=mg(s),s=wg(this._host,this._type,s,i,xd),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};ef([hd(new Ed)],tf.prototype,"host",null),ef([hd(new Ed)],tf.prototype,"port",null),ef([hd(new Ed)],tf.prototype,"type",null),ef([hd(new Ed)],tf.prototype,"send",null),ef([hd(new Ed)],tf.prototype,"send_",null),tf=ef([ld({eventStart:class extends Rg{},eventStarted:class extends Rg{},eventStop:class extends Rg{},eventStopped:Og})],tf);const rf=tf,sf=new WeakMap;const nf=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(sf.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);sf.set(i,r)};class of extends wu{static description="Contexts error"}class af extends of{static description="Aborted due to timer expiration"}const cf=function(e=!1,t=1/0,r=af){return(s,i,n)=>{const o=s.name??s.constructor.name,a=n.value;if("function"!=typeof a)throw new TypeError(`\`${o}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=sf.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,o);return n.value=function(...s){let n=s[c];return n=void 0===n?{}:{...n},s[c]=n,function(e,t,r){if("object"!=typeof e||null===e)throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter is not a context object`);if(void 0!==e.signal&&!(e.signal instanceof AbortSignal))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`signal\` property is not an instance of \`AbortSignal\``);if(void 0!==e.timer&&!("number"==typeof e.timer||e.timer instanceof xu))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,o),function(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new xu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof xu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new xu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new mu((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}((e,...t)=>a.apply(this,t),"boolean"==typeof e?e:e(this),"number"==typeof t?t:t(this),r,n,s)},Object.defineProperty(n.value,"name",{value:"symbol"==typeof i?`[${i.description}]`:i}),n}},lf=["rsa_pkcs1_sha256","rsa_pkcs1_sha384","rsa_pkcs1_sha512","rsa_pss_rsae_sha256","rsa_pss_rsae_sha384","rsa_pss_rsae_sha512","ecdsa_secp256r1_sha256","ecdsa_secp384r1_sha384","ecdsa_secp521r1_sha512","ed25519"].join(":"),hf=1/0,uf={sigalgs:lf,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:pd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:pd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:pd.MAX_CONNECTION_WINDOW,maxStreamWindow:pd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},df={sigalgs:lf,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:pd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:pd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:pd.MAX_CONNECTION_WINDOW,maxStreamWindow:pd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},gf=t(import.meta.url)("stream/web");var ff=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};const pf=Symbol("abort readableP reason");let yf=class{static createQUICStream({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i=()=>0,codeToReason:n=(e,t)=>new Error(`${e.toString()} ${t.toString()}`),logger:o=new zh(`${this.name} ${t}`)}){o.info(`Create ${this.name}`);const a=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o});return"uni"===a.type&&("local"===e?(a.readableController.close(),a._readClosed=!0):"peer"===e&&(a.writable.close().catch(()=>{}),a._writeClosed=!0)),a.addEventListener(Jg.name,a.handleEventQUICStreamError),a.addEventListener(Yg.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(Zg.name,a.handleEventQUICStreamCloseWrite,{once:!0}),o.info(`Created ${this.name}`),a}type;initiated;streamId;readable;writable;closedP;logger;connection;reasonToCode;codeToReason;readableController;writableController;_readClosed=!1;_writeClosed=!1;readableChunk;resolveReadableP;rejectReadableP;resolveWritableP;rejectWritableP;resolveClosedP;handleEventQUICStreamError=e=>{const t=e.detail;if(t instanceof ng)throw this.logger.debug(Cg(t)),t;t instanceof tg||t instanceof sg?this.dispatchEvent(new Yg({detail:t})):(t instanceof rg||t instanceof ig)&&this.dispatchEvent(new Zg({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=o,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:a,resolveP:c}=ug();if(this.closedP=a,this.resolveClosedP=c,"uni"===this.type&&"local"===e?this.readableChunk=void 0:this.readableChunk=Buffer.allocUnsafe(s.readableChunkSize),"uni"===this.type&&"local"===e?this.readable=new gf.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new gf.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new gf.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new gf.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new gf.WritableStream({start:this.writableStart.bind(this),write:this.writableWrite.bind(this),close:this.writableClose.bind(this),abort:this.writableAbort.bind(this)},{highWaterMark:1});try{r.conn.streamSend(t,new Uint8Array(0),!1)}catch(e){if(!1===kg(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new og(`Stream limit of ${t} has been reached`,{cause:e})}throw new ng(`Failed to prime local stream state with a 0-length message: ${e.message}`,{cause:e})}}}}get writeClosed(){return this._writeClosed}get readClosed(){return this._readClosed}get meta(){return this.connection.meta()}get closed(){return this._readClosed&&this._writeClosed}async destroy({force:e=!0,reason:t}={}){this.logger.info(`Destroy ${this.constructor.name}`),!e||this._readClosed&&this._writeClosed||this.cancel(t),await this.closedP,this.removeEventListener(Jg.name,this.handleEventQUICStreamError),this.removeEventListener(Yg.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(Zg.name,this.handleEventQUICStreamCloseWrite),this.logger.info(`Destroyed ${this.constructor.name}`)}cancel(e){this.readableCancel(e),this.writableAbort(e)}read(){if(this.connection.conn.streamFinished(this.streamId)){let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=xg(e))){const e=this.codeToReason("read",t),r=new sg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new Jg({detail:r}))}{const t=new ng("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new Jg({detail:t})),t}}if(null===e){const e=new ng("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Jg({detail:e})),e}const[t]=e;return t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),this.readableController.close(),this.dispatchEvent(new Yg),void this.rejectReadableP?.(pf)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=kg(e))){this.connection.conn.streamShutdown(this.streamId,pd.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new ig("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new Jg({detail:r}))}{const t=new ng("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new Jg({detail:t})),t}}this.resolveWritableP?.()}readableStart(e){this.readableController=e}writableStart(e){this.writableController=e}async readablePull(){if(!this.connection.conn.streamReadable(this.streamId)){const{p:e,resolveP:t,rejectP:r}=ug();e.catch(()=>{}),this.resolveReadableP=t,this.rejectReadableP=r;try{await e}catch(e){return}}let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=xg(e))){const e=this.codeToReason("read",t),r=new sg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new Jg({detail:r}))}{const t=new ng("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new Jg({detail:t})),t}}if(null===e){const e=new ng("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new Jg({detail:e})),e}const[t,r]=e;t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),r&&(this.readableController.close(),this.dispatchEvent(new Yg)),this.dispatchEvent(new Xg)}async writableWrite(e){if(0===e.byteLength)return;let t;for(;;){try{const r=this.connection.conn.streamSend(this.streamId,e,!1);t=null===r?0:r}catch(e){let t;if(!1!==(t=kg(e))){const e=this.codeToReason("write",t),r=new ig("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Jg({detail:r}))}{const t=new ng("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Jg({detail:t})),t}}if(this.dispatchEvent(new Xg),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=ug();r.catch(()=>{}),this.resolveWritableP=s,this.rejectWritableP=i,await r;continue}return}}writableClose(){try{this.connection.conn.streamSend(this.streamId,new Uint8Array(0),!0)}catch(e){let t;if(!1!==(t=kg(e))){const e=this.codeToReason("write",t),r=new ig("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Jg({detail:r}))}{const t=new ng("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Jg({detail:t})),t}}this.dispatchEvent(new Zg),this.dispatchEvent(new Xg)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,pd.Shutdown.Read,t)}catch(r){const e=new ng("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new Jg({detail:e})),e}const r=new tg("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Jg({detail:r})),this.dispatchEvent(new Xg)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,pd.Shutdown.Write,t)}catch(r){const e=new ng("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new Jg({detail:e})),e}const r=new rg("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new Jg({detail:r})),this.dispatchEvent(new Xg)}};ff([cd(new eg)],yf.prototype,"meta",null),ff([cd(new eg,!1,["destroying"])],yf.prototype,"read",null),ff([cd(new eg,!1,["destroying"])],yf.prototype,"write",null),yf=ff([ad({eventDestroy:class extends zg{},eventDestroyed:Wg})],yf);const mf=yf;var bf,Af,If,vf,wf,Sf;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(bf||(bf={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Af||(Af={})),function(e){e[e.Initial=0]="Initial",e[e.Retry=1]="Retry",e[e.Handshake=2]="Handshake",e[e.ZeroRTT=3]="ZeroRTT",e[e.VersionNegotiation=4]="VersionNegotiation",e[e.Short=5]="Short"}(If||(If={})),function(e){e[e.NoError=0]="NoError",e[e.InternalError=1]="InternalError",e[e.ConnectionRefused=2]="ConnectionRefused",e[e.FlowControlError=3]="FlowControlError",e[e.StreamLimitError=4]="StreamLimitError",e[e.StreamStateError=5]="StreamStateError",e[e.FinalSizeError=6]="FinalSizeError",e[e.FrameEncodingError=7]="FrameEncodingError",e[e.TransportParameterError=8]="TransportParameterError",e[e.ConnectionIdLimitError=9]="ConnectionIdLimitError",e[e.ProtocolViolation=10]="ProtocolViolation",e[e.InvalidToken=11]="InvalidToken",e[e.ApplicationError=12]="ApplicationError",e[e.CryptoBufferExceeded=13]="CryptoBufferExceeded",e[e.KeyUpdateError=14]="KeyUpdateError",e[e.AEADLimitReached=15]="AEADLimitReached",e[e.NoViablePath=16]="NoViablePath"}(vf||(vf={})),(Sf=wf||(wf={}))[Sf.CloseNotify=256]="CloseNotify",Sf[Sf.UnexpectedMessage=266]="UnexpectedMessage",Sf[Sf.BadRecordMac=276]="BadRecordMac",Sf[Sf.RecordOverflow=278]="RecordOverflow",Sf[Sf.HandshakeFailure=296]="HandshakeFailure",Sf[Sf.BadCertificate=298]="BadCertificate",Sf[Sf.UnsupportedCertificate=299]="UnsupportedCertificate",Sf[Sf.CertificateRevoked=300]="CertificateRevoked",Sf[Sf.CertificateExpired=301]="CertificateExpired",Sf[Sf.CertificateUnknown=302]="CertificateUnknown",Sf[Sf.IllegalParameter=303]="IllegalParameter",Sf[Sf.UnknownCA=304]="UnknownCA",Sf[Sf.AccessDenied=305]="AccessDenied",Sf[Sf.DecodeError=306]="DecodeError",Sf[Sf.DecryptError=307]="DecryptError",Sf[Sf.ProtocolVersion=326]="ProtocolVersion",Sf[Sf.InsufficientSecurity=327]="InsufficientSecurity",Sf[Sf.InternalError=336]="InternalError",Sf[Sf.InappropriateFallback=342]="InappropriateFallback",Sf[Sf.UserCanceled=346]="UserCanceled",Sf[Sf.MissingExtension=365]="MissingExtension",Sf[Sf.UnsupportedExtension=366]="UnsupportedExtension",Sf[Sf.UnrecognizedName=368]="UnrecognizedName",Sf[Sf.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",Sf[Sf.UnknownPSKIdentity=371]="UnknownPSKIdentity",Sf[Sf.CertificateRequired=372]="CertificateRequired",Sf[Sf.NoApplicationProtocol=376]="NoApplicationProtocol";var Ef=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Cf=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Tu;streamIdClientBidi=0;streamIdServerBidi=1;streamIdClientUni=2;streamIdServerUni=3;streamIdUsedClientBidi=-4;streamIdUsedServerBidi=-3;streamIdUsedClientUni=-2;streamIdUsedServerUni=-1;streamIdUsedSet=new Set;connTimeoutTimer;keepAliveIntervalTimer;_remoteHost;_remotePort;certDERs=[];caDERs=[];secureEstablished=!1;secureEstablishedP;resolveSecureEstablishedP;rejectSecureEstablishedP;resolveClosedP;errorLast=null;handleEventQUICConnectionError=e=>{const t=e.detail;if(this.errorLast=t,this.logger.info(Cg(t)),t instanceof Zd)throw t;this.dispatchEvent(new $g({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof qd&&await this.send(),this[Mu]&&"stopping"!==this[Ku]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof Jh&&!(e.detail instanceof Xg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[Mu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(Xg.name,this.handleEventQUICStreamSend),t.removeEventListener(eu.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:o,reasonToCode:a=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new zh(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new jd("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new wd("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new wd("The key option must be set when cert is set");if(null!=e.key&&null!=e.cert&&Array.isArray(e.key)&&Array.isArray(e.cert)&&e.key.length!==e.cert.length)throw new wd("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Sg(e.ca);t=ag.encode(r.join(""))}null!=e.key&&(r=Sg(e.key).map(e=>ag.encode(e))),null!=e.cert&&(s=Sg(e.cert).map(e=>ag.encode(e)));try{i=pd.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new wd(`Failed to build Quiche config with custom SSL context: ${e.message}`,{cause:e})}return null!=e.logKeys&&i.logKeys(),e.enableEarlyData&&i.enableEarlyData(),i.grease(e.grease),i.setMaxIdleTimeout(e.maxIdleTimeout),i.setMaxRecvUdpPayloadSize(e.maxRecvUdpPayloadSize),i.setMaxSendUdpPayloadSize(e.maxSendUdpPayloadSize),i.setInitialMaxData(e.initialMaxData),i.setInitialMaxStreamDataBidiLocal(e.initialMaxStreamDataBidiLocal),i.setInitialMaxStreamDataBidiRemote(e.initialMaxStreamDataBidiRemote),i.setInitialMaxStreamDataUni(e.initialMaxStreamDataUni),i.setInitialMaxStreamsBidi(e.initialMaxStreamsBidi),i.setInitialMaxStreamsUni(e.initialMaxStreamsUni),i.enableDgram(...e.enableDgram),i.setDisableActiveMigration(e.disableActiveMigration),i.setApplicationProtos(e.applicationProtos),i}(n);let u;if("client"===e?(this.logger.info(`Connect ${this.constructor.name}`),u=pd.Connection.connect(s,t,{host:o.host,port:o.port},{host:i.host,port:i.port},h)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=pd.Connection.accept(t,r,{host:o.host,port:o.port},{host:i.host,port:i.port},h)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=o,this.config=n,null!=this.config.cert){const e=Sg(this.config.cert);this.certDERs=e.map(Eg)}if(null!=this.config.ca){const e=Sg(this.config.ca);this.caDERs=e.map(Eg)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:g,rejectP:f}=ug();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,g()},this.rejectSecureEstablishedP=f;const{p,resolveP:y}=ug();this.closedP=p,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new dd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new dd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new dd(Buffer.concat([e,t])):new dd(Buffer.concat([t,e]))}get remoteHost(){return this._remoteHost}get remotePort(){return this._remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this.conn.isClosed()}async start({data:e,remoteInfo:t}={},r){if(this.logger.info(`Start ${this.constructor.name}`),this.conn.isClosed())throw new Gd;r.signal.throwIfAborted();const{p:s,rejectP:i}=ug();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Gg.name,this.handleEventQUICConnectionError),this.addEventListener($g.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new $d("Starting a server connection requires initial data and remote information");await this.recv(e,t)}try{await Promise.race([this.secureEstablishedP,s])}catch(e){if(r.signal.aborted){for(const t of this.conn.readable())this.conn.streamShutdown(t,pd.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,pd.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,vf.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new qd("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Gg({detail:r}))}throw await this.closedP,e}finally{r.signal.removeEventListener("abort",n)}null!=this.config.keepAliveIntervalTime&&this.startKeepAliveIntervalTimer(this.config.keepAliveIntervalTime),this.logger.info(`Started ${this.constructor.name}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){this.logger.info(`Stop ${this.constructor.name}`),this.stopKeepAliveIntervalTimer(),await async function(){return await new Promise(e=>queueMicrotask(e))}();const i=[];for(const e of this.streamMap.values())i.push(e.destroy({reason:this.errorLast,force:s||this.conn.isDraining()||this.conn.isClosed()}));if(await Promise.all(i),!this.conn.isDraining()&&!this.conn.isClosed()){this.conn.close(e,t,r);const s=this.conn.localError(),i=`Locally closed with ${s.isApp?"application":"transport"} code ${s.errorCode}`,n=new qd(i,{data:s});this.dispatchEvent(new Gg({detail:n}))}await this.closedP,this.removeEventListener(Gg.name,this.handleEventQUICConnectionError),this.removeEventListener($g.name,this.handleEventQUICConnectionClose),this.logger.info(`Stopped ${this.constructor.name}`)}getConnectionError(){return this.conn.localError()??this.conn.peerError()??void 0}getLocalCACertsChain(){return this.caDERs}getLocalCertsChain(){return this.certDERs}getRemoteCertsChain(){return this.conn.peerCertChain()??[]}meta(){return{localHost:this.localHost,localPort:this.localPort,remoteHost:this.remoteHost,remotePort:this.remotePort,localCertsChain:this.certDERs,localCACertsChain:this.caDERs,remoteCertsChain:this.getRemoteCertsChain()}}async recv(e,t){await this.recvLock.withF(async()=>{const r={to:{host:this.localHost,port:this.localPort},from:{host:t.host,port:t.port}};try{this.conn.recv(e,r)}catch(e){const t=this.conn.localError();if(null==t){const t=new Zd("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Gg({detail:t})),t}{let r;return r="TlsFail"===e.message?new zd("Failed connection due to native TLS verification",{cause:e,data:t}):new qd("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Gg({detail:r}))}}this._remoteHost=t.host,this._remotePort=t.port,!this.secureEstablished&&this.conn.isEstablished()&&null==this.config.verifyCallback&&this.resolveSecureEstablishedP(),this.secureEstablished&&this.processStreams(),await this.send()})}async send(){let e,t;for(;;){const r=Buffer.allocUnsafe(this.config.maxSendUdpPayloadSize);try{const s=this.conn.send(r);if(null===s)break;[e,t]=s}catch(e){const t=new Zd("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Gg({detail:t})),t}this.dispatchEvent(new qg({detail:{id:this.sendId,msg:r.subarray(0,e),port:t.to.port,address:t.to.host}}))}if(this.setConnTimeoutTimer(),!this.secureEstablished&&!this.conn.isDraining()&&!this.conn.isClosed()&&this.conn.isEstablished()&&this.config.verifyPeer&&null!=this.config.verifyCallback){const e=this.conn.peerCertChain(),t=await this.config.verifyCallback(e,this.caDERs);if(null!=t){this.conn.close(!1,t,Buffer.from(""));const e=this.conn.localError(),r=new zd("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Gg({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[Ku]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=pd.CRYPTO_ERROR_START&&e.errorCode<=pd.CRYPTO_ERROR_STOP?this.dispatchEvent(new Gg({detail:new Jd(t,{data:e})})):this.dispatchEvent(new Gg({detail:new Wd(t,{data:e})})))}}}isStreamUsed(e){let t;switch(3&e){case 0:if(t=this.streamIdUsedClientBidi+4,e<=this.streamIdUsedClientBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 1:if(t=this.streamIdUsedServerBidi+4,e<=this.streamIdUsedServerBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 2:if(t=this.streamIdUsedClientUni+4,e<=this.streamIdUsedClientUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 3:if(t=this.streamIdUsedServerUni+4,e<=this.streamIdUsedServerUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;default:lg("got an unexpected ID type")}}processStreams(){for(const e of this.conn.readable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Mu]||"stopping"===this[Ku]){this.conn.streamShutdown(e,Af.Write,this.reasonToCode("write",Qd)),this.conn.streamShutdown(e,Af.Read,this.reasonToCode("read",Qd));continue}this.isStreamUsed(e)&&lg("We should never repeat streamIds when creating streams"),t=mf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Xg.name,this.handleEventQUICStreamSend),t.addEventListener(Wg.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(eu.name,this.handleEventQUICStream),this.dispatchEvent(new jg({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Mu]||"stopping"===this[Ku]){this.conn.streamShutdown(e,Af.Write,this.reasonToCode("write",Qd)),this.conn.streamShutdown(e,Af.Read,this.reasonToCode("read",Qd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==kg(e))continue;if("FinalSize"===e.message)continue;throw e}lg("We never expect a duplicate stream to be readable")}t=mf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Xg.name,this.handleEventQUICStreamSend),t.addEventListener(Wg.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(eu.name,this.handleEventQUICStream),this.dispatchEvent(new jg({detail:t}))}t.write()}}setConnTimeoutTimer(){const e=async t=>{if(t.aborted)return;if(this.conn.onTimeout(),this.conn.isClosed())return this.resolveClosedP(),void(this.conn.isTimedOut()&&this.dispatchEvent(new Gg({detail:new Yd})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new xu({delay:r+1,handler:e,lazy:!0}))},t=this.conn.timeout();if(null==t)return this.connTimeoutTimer?.cancel(),delete this.connTimeoutTimer,void(this.conn.isClosed()&&(this.resolveClosedP(),this.conn.isTimedOut()&&this.dispatchEvent(new Gg({detail:new Yd}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new xu({delay:t+1,handler:e,lazy:!0}):null==this.connTimeoutTimer.status&&this.connTimeoutTimer.reset(t+1)}newStream(e="bidi"){let t;"client"===this.type&&"bidi"===e?t=this.streamIdClientBidi:"server"===this.type&&"bidi"===e?t=this.streamIdServerBidi:"client"===this.type&&"uni"===e?t=this.streamIdClientUni:"server"===this.type&&"uni"===e&&(t=this.streamIdServerUni),this.isStreamUsed(t)&&lg("We should never repeat streamIds when creating streams");const r=mf.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mf.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(Xg.name,this.handleEventQUICStreamSend),r.addEventListener(Wg.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(eu.name,this.handleEventQUICStream),"client"===this.type&&"bidi"===e?this.streamIdClientBidi=this.streamIdClientBidi+4:"server"===this.type&&"bidi"===e?this.streamIdServerBidi=this.streamIdServerBidi+4:"client"===this.type&&"uni"===e?this.streamIdClientUni=this.streamIdClientUni+4:"server"===this.type&&"uni"===e&&(this.streamIdServerUni=this.streamIdServerUni+4),r}destroyStreams(e){for(const t of this.streamMap.values())t.cancel(e)}startKeepAliveIntervalTimer(e){const t=async r=>{r.aborted||(this.conn.sendAckEliciting(),await this.send(),r.aborted||(this.keepAliveIntervalTimer=new xu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new xu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var kf,xf;Ef([hd(new Fd)],Cf.prototype,"connectionIdPeer",null),Ef([hd(new Fd)],Cf.prototype,"connectionIdShared",null),Ef([cf(!0,hf,class extends Vd{static description="QUIC Connection start timeout"}),(kf=1,xf=nf,function(e,t){xf(e,t,kf)})],Cf.prototype,"start",null),Ef([hd(new Fd,!1,["starting","stopping"])],Cf.prototype,"recv",null),Ef([hd(new Fd,!1,["starting","stopping"])],Cf.prototype,"send",null),Ef([hd(new Fd)],Cf.prototype,"newStream",null),Cf=Ef([ld({eventStart:class extends Qg{},eventStarted:class extends Qg{},eventStop:class extends Qg{},eventStopped:Fg})],Cf);const Bf=Cf;var _f=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Rf=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(Cg(t)),t instanceof Hd)throw t;this.dispatchEvent(new Vg({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof Pd||this.isSocketShared)){this.socket.removeEventListener(Og.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Hd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Kg({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Mu]&&"stopping"!==this[Ku]&&(void 0!==t?await this.stop({isApp:!1,errorCode:vf.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof Jh&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Pd;this.removeEventListener(eu.name,this.handleEventQUICSocket),this.dispatchEvent(new Kg({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Jh&&!(e.detail instanceof qg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[Mu]&&"stopping"!==this.socket[Ku])try{await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Mg(`${Mg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Kg({detail:new Hd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(qg.name,this.handleEventQUICConnectionSend),t.removeEventListener(eu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=bg,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new zh(this.constructor.name),this.crypto=e,null==r?(this.socket=new rf({resolveHostname:s,logger:this.logger.getChild(rf.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...df,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=ug();this._closedP=c,this.resolveClosedP=l}get host(){return this.socket.host}get port(){return this.socket.port}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r,ipv6Only:s}={}){let i;if(this.stopAbortController=new AbortController,Bg(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[Mu])throw new Pd;i=vg(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=vg(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=vg(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(Kg.name,this.handleEventQUICServerError),this.addEventListener(Vg.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Og.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(eu.name,this.handleEventQUICSocket),this._closed=!1,this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.socket[Mu]&&(i=vg(this.socket.host,this.socket.port)),this.logger.info(`Stop ${this.constructor.name}${null!=i?` on ${i}`:""}`),this.socket.unsetServer();const n=[];s&&this.stopAbortController?.abort(new Kd),this.stopAbortController=void 0;for(const i of this.socket.connectionMap.serverConnections.values())n.push(i.stop({isApp:e,errorCode:t,reason:r,force:s}));await Promise.all(n),this._closed||this.dispatchEvent(new Vg),await this._closedP;const{p:o,resolveP:a}=ug();this._closedP=o,this.resolveClosedP=a,this.removeEventListener(Kg.name,this.handleEventQUICServerError),this.removeEventListener(Vg.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Og.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(eu.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==pd.Type.Initial&&t.ty!==pd.Type.ZeroRTT)return;const i=new dd(await this.crypto.ops.sign(this.crypto.key,r),0,pd.MAX_CONN_ID_LEN),n=vg(e.host,e.port);if(!pd.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(pd.MAX_DATAGRAM_SIZE),s=pd.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new Ld(`Failed to send version datagram ${n}`,{cause:e})}return}const o=t.token;if(0===o.byteLength){const s=await this.mintToken(r,e.host),o=Buffer.allocUnsafe(pd.MAX_DATAGRAM_SIZE),a=pd.retry(t.scid,t.dcid,i,s,t.version,o);try{await this.socket.send_(o,0,a,e.port,e.host)}catch(e){throw new Ld(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const a=await this.validateToken(Buffer.from(o),e.host);if(null==a)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new dd(t.dcid),l=new Bf({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${Bf.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(qg.name,this.handleEventQUICConnectionSend),l.addEventListener(Fg.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(eu.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(qg.name,this.handleEventQUICConnectionSend),l.removeEventListener(Fg.name,this.handleEventQUICConnectionStopped),l.removeEventListener(eu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new Ld("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Hg({detail:l})),l}updateCrypto(e){this.crypto={...this.crypto,...e}}updateConfig(e){this.config={...this.config,...e}}async mintToken(e,t){return async function(e,t,r){const s={dcid:e.toString(),host:t},i=JSON.stringify(s),n=Buffer.from(i),o=Buffer.from(await r.ops.sign(r.key,n)),a={msg:n.toString("base64url"),sig:o.toString("base64url")},c=JSON.stringify(a);return Buffer.from(c)}(e,t,this.crypto)}async validateToken(e,t){return async function(e,t,r){let s;try{s=JSON.parse(e.toString())}catch{return}if("object"!=typeof s||null==s)return;if("string"!=typeof s.msg||"string"!=typeof s.sig)return;const i=Buffer.from(s.msg,"base64url"),n=Buffer.from(s.sig,"base64url");if(!await r.ops.verify(r.key,i,n))return;let o;try{o=JSON.parse(i.toString())}catch{return}return"object"==typeof o&&null!=o&&"string"==typeof o.dcid&&"string"==typeof o.host&&o.host===t?dd.fromString(o.dcid):void 0}(e,t,this.crypto)}};_f([hd(new Md)],Rf.prototype,"host",null),_f([hd(new Md)],Rf.prototype,"port",null),_f([hd(new Md)],Rf.prototype,"acceptConnection",null),Rf=_f([ld({eventStart:class extends Lg{},eventStarted:class extends Lg{},eventStop:class extends Lg{},eventStopped:class extends Lg{}})],Rf);var Of=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Uf=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=bg,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:g=new zh(`${this.name}`)},f){let p=vg(e,t);g.info(`Create ${this.name} to ${p}`);const y={...uf,...a},m=new ArrayBuffer(pd.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new dd(m);let[A,I]=await Ag(e,c);const v=Ig(t);let w,S;if(A=mg(A),null==n){const[e]=await Ag(s,c),t=Ig(i);n=new rf({resolveHostname:c,logger:g.getChild(rf.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[Mu])throw new Pd;try{A=wg(n.host,n.type,A,I,Td)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new Bf({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:g.getChild(`${Bf.name} ${b.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:g});w||n.addEventListener(eu.name,E.handleEventQUICSocket),n.addEventListener(Og.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(eu.name,E.handleEventQUICConnection),S.addEventListener(Gg.name,E.handleEventQUICConnectionError),S.addEventListener(qg.name,E.handleEventQUICConnectionSend),S.addEventListener(Fg.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(Dg.name,E.handleEventQUICClientError),E.addEventListener(Pg.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(f.signal.reason)};f.signal.aborted?C.abort(f.signal.reason):f.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Ud(void 0,{cause:e.detail}))}};E.addEventListener(`${Mg.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:f.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Og.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(eu.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(eu.name,E.handleEventQUICConnection),S.removeEventListener(Gg.name,E.handleEventQUICConnectionError),S.removeEventListener(qg.name,E.handleEventQUICConnectionSend),S.removeEventListener(Fg.name,E.handleEventQUICConnectionStopped),E.removeEventListener(Dg.name,E.handleEventQUICClientError),E.removeEventListener(Pg.name,E.handleEventQUICClientClose),e}finally{f.signal.removeEventListener("abort",k),E.removeEventListener(`${Mg.name}-${S.sendId}`,x)}return p=vg(A,t),g.info(`Created ${this.name} to ${p}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(Cg(t)),t instanceof Nd||t instanceof Zd)throw t;this.dispatchEvent(new Pg({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Gg.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:vf.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Od||this.isSocketShared)){this.socket.removeEventListener(Og.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Nd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Dg({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof Jh&&!(e.detail instanceof qg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Od;this.removeEventListener(eu.name,this.handleEventQUICSocket),this.dispatchEvent(new Dg({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Jh&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new Dg({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[Mu]||"stopping"===this.socket[Ku])return;await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Mg(`${Mg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Dg({detail:new Nd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Gg.name,this.handleEventQUICConnectionError),t.removeEventListener(qg.name,this.handleEventQUICConnectionSend),t.removeEventListener(eu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({socket:e,isSocketShared:t,connection:r,logger:s}){this.logger=s,this.socket=e,this.isSocketShared=t,this.connection=r;const{p:i,resolveP:n}=ug();this.closedP=i,this.resolveClosedP=n}get host(){return this.connection.remoteHost}get port(){return this.connection.remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this._closed}async destroy({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.connection[Mu]&&(i=vg(this.connection.remoteHost,this.connection.remotePort)),this.logger.info(`Destroy ${this.constructor.name}${null!=i?` to ${i}`:""}`),this._closed||await this.connection.stop({isApp:e,errorCode:t,reason:r,force:s}),await this.closedP,this.removeEventListener(Dg.name,this.handleEventQUICClientError),this.removeEventListener(Pg.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Og.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(eu.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Of([cd(new Rd)],Uf.prototype,"host",null),Of([cd(new Rd)],Uf.prototype,"port",null),Of([cd(new Rd)],Uf.prototype,"localHost",null),Of([cd(new Rd)],Uf.prototype,"localPort",null),Of([cf(!0,hf,class extends _d{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,nf)],Uf,"createQUICClient",null),Uf=Of([ad({eventDestroy:class extends Ng{},eventDestroyed:class extends Ng{}})],Uf),t(import.meta.url)("node:crypto");class Tf{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const r=Tf.toUint8Array(e),s=Tf.toUint8Array(t);if(r.length!==s.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const s=new Uint8Array(r);let i=0;for(const e of t){const t=this.toUint8Array(e);s.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const Nf="string",Df=/^[0-9a-f\s]+$/i,Mf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Pf=/^[a-zA-Z0-9-_]+$/;class Lf{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=Tf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class Hf{static toString(e,t=!1){const r=Tf.toArrayBuffer(e),s=new DataView(r);let i="";for(let e=0;e<r.byteLength;e+=2){const r=s.getUint16(e,t);i+=String.fromCharCode(r)}return i}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),s=new DataView(r);for(let r=0;r<e.length;r++)s.setUint16(2*r,e.charCodeAt(r),t);return r}}class Kf{static isHex(e){return typeof e===Nf&&Df.test(e)}static isBase64(e){return typeof e===Nf&&Mf.test(e)}static isBase64Url(e){return typeof e===Nf&&Pf.test(e)}static ToString(e,t="utf8"){const r=Tf.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return Hf.toString(r,!0);case"utf16":case"utf16be":return Hf.toString(r);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Hf.fromString(e,!0);case"utf16":case"utf16be":return Hf.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=Tf.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kf.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kf.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=Kf.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Lf.fromString(e);case"utf16":case"utf16be":return Hf.fromString(e);case"utf16le":case"usc2":return Hf.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Kf.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Lf.toString(e);case"utf16":case"utf16be":return Hf.toString(e);case"utf16le":case"usc2":return Hf.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return r.buffer}static ToBinary(e){const t=Tf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=Tf.toUint8Array(e);let r="";const s=t.length;for(let e=0;e<s;e++){const s=t[e];s<16&&(r+="0"),r+=s.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kf.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const s=t.slice(e,e+2);r[e/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(e,t=!1){return Hf.toString(e,t)}static FromUtf16String(e,t=!1){return Hf.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function Vf(...e){const t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(t);let s=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(const t of e)r[s++]=t}),r.buffer}function Qf(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}function Ff(e,t){let r=0;if(1===e.length)return e[0];for(let s=e.length-1;s>=0;s--)r+=e[e.length-1-s]*Math.pow(2,t*s);return r}function Gf(e,t,r=-1){const s=r;let i=e,n=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e<o){let e;if(s<0)e=new ArrayBuffer(r),n=r;else{if(s<r)return new ArrayBuffer(0);e=new ArrayBuffer(s),n=s}const o=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);o[n-e-1]=Math.floor(i/r),i-=o[n-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function $f(...e){let t=0,r=0;for(const r of e)t+=r.length;const s=new ArrayBuffer(t),i=new Uint8Array(s);for(const t of e)i.set(t,r),r+=t.length;return i}function jf(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const s=Ff(r,8),i=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)n[t]=e[t];return n[0]&=127,Ff(n,8)-s}function qf(e,t){const r=e.toString(10);if(t<r.length)return"";const s=t-r.length,i=new Array(s);for(let e=0;e<s;e++)i[e]="0";return i.join("").concat(r)}function zf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Wf(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const s=new Uint8Array(t);for(let t=0;t<e.length;t++){const i=e[t];s.set(new Uint8Array(i),r),r+=i.byteLength}return s.buffer}function Jf(e,t,r,s){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):s<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-s<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}Kf.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Yf{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wf(this.items)}}const Zf=[new Uint8Array([1])],Xf="0123456789",ep="name",tp="valueHexView",rp="isHexOnly",sp="idBlock",ip="tagClass",np="tagNumber",op="isConstructed",ap="fromBER",cp="toBER",lp="local",hp="",up=new ArrayBuffer(0),dp=new Uint8Array(0),gp="EndOfContent",fp="OCTET STRING",pp="BIT STRING";function yp(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?Tf.toUint8Array(r.valueHex):dp}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Jf(this,s,t,r))return-1;const i=t+r;return this.valueHexView=s.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",up)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Kf.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class mp{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=hp,warnings:r=[],valueBeforeDecode:s=dp}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Tf.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Kf.ToHex(this.valueBeforeDecodeView)}}}mp.NAME="baseBlock";class bp extends mp{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}bp.NAME="valueBlock";class Ap extends(yp(mp)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?Tf.toUint8Array(e.valueHex):dp,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(s=e.tagNumber)&&void 0!==s?s:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",up}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=Gf(this.tagNumber,7),s=new Uint8Array(r),i=r.byteLength,n=new Uint8Array(i+1);if(n[0]=31|t,!e){for(let e=0;e<i-1;e++)n[e+1]=128|s[e];n[i]=s[i-1]}return n.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const s=Tf.toUint8Array(e);if(!Jf(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;const n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&i[e];){if(t[e-1]=127&i[e],e++,e>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&i[e];const s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(s),this.blockLength<=9?this.tagNumber=Ff(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Ap.NAME="identificationBlock";class Ip extends mp{constructor({lenBlock:e={}}={}){var t,r,s;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(s=e.length)&&void 0!==s?s:0}fromBER(e,t,r){const s=Tf.toUint8Array(e);if(!Jf(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;const n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=s.subarray(o,o+n);return 0===a[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=Ff(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const s=Gf(this.length,8);if(s.byteLength>127)return this.error="Too big length",up;if(t=new ArrayBuffer(s.byteLength+1),e)return t;const i=new Uint8Array(s);r=new Uint8Array(t),r[0]=128|s.byteLength;for(let e=0;e<s.byteLength;e++)r[e+1]=i[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Ip.NAME="lengthBlock";const vp={};class wp extends mp{constructor({name:e=hp,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Ap(s),this.lenBlock=new Ip(s),this.valueBlock=i?new i(s):new bp(s)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){const r=t||new Yf;t||Sp(this);const s=this.idBlock.toBER(e);if(r.write(s),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const s=this.lenBlock.toBER(e);r.write(s),r.write(t)}return t?up:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():Kf.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Kf.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}(this.toBER(),e.toBER())}}function Sp(e){var t;if(e instanceof vp.Constructed)for(const t of e.valueBlock.value)Sp(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}wp.NAME="BaseBlock";class Ep extends wp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=hp,...t}={},r){super(t,r),e&&this.fromString(e)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Ep.NAME="BaseStringBlock";class Cp extends(yp(bp)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var kp,xp,Bp,_p,Rp,Op,Up,Tp,Np,Dp,Mp,Pp,Lp,Hp,Kp,Vp,Qp,Fp,Gp,$p,jp,qp,zp,Wp,Jp,Yp,Zp,Xp,ey,ty,ry,sy,iy,ny,oy,ay;Cp.NAME="PrimitiveValueBlock";class cy extends wp{constructor(e={}){super(e,Cp),this.idBlock.isConstructed=!1}}function ly(e,t=0,r=e.length){const s=t;let i=new wp({},bp);const n=new mp;if(!Jf(n,e,t,r))return i.error=n.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let o=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===o)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=o,r-=i.idBlock.blockLength,o=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===o)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=o,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let a=wp;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};a=vp.EndOfContent;break;case 1:a=vp.Boolean;break;case 2:a=vp.Integer;break;case 3:a=vp.BitString;break;case 4:a=vp.OctetString;break;case 5:a=vp.Null;break;case 6:a=vp.ObjectIdentifier;break;case 10:a=vp.Enumerated;break;case 12:a=vp.Utf8String;break;case 13:a=vp.RelativeObjectIdentifier;break;case 14:a=vp.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=vp.Sequence;break;case 17:a=vp.Set;break;case 18:a=vp.NumericString;break;case 19:a=vp.PrintableString;break;case 20:a=vp.TeletexString;break;case 21:a=vp.VideotexString;break;case 22:a=vp.IA5String;break;case 23:a=vp.UTCTime;break;case 24:a=vp.GeneralizedTime;break;case 25:a=vp.GraphicString;break;case 26:a=vp.VisibleString;break;case 27:a=vp.GeneralString;break;case 28:a=vp.UniversalString;break;case 29:a=vp.CharacterString;break;case 30:a=vp.BmpString;break;case 31:a=vp.DATE;break;case 32:a=vp.TimeOfDay;break;case 33:a=vp.DateTime;break;case 34:a=vp.Duration;break;default:{const e=i.idBlock.isConstructed?new vp.Constructed:new vp.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?vp.Constructed:vp.Primitive;return i=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,a),o=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:o,result:i}}function hy(e){if(!e.byteLength){const e=new wp({},bp);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ly(Tf.toUint8Array(e).slice(),0,e.byteLength)}function uy(e,t){return e?1:t}kp=cy,vp.Primitive=kp,cy.NAME="PRIMITIVE";class dy extends bp{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=Tf.toUint8Array(e);if(!Jf(this,s,t,r))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let i=t;for(;uy(this.isIndefiniteForm,r)>0;){const e=ly(s,i,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(i=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===gp)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===gp?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Yf;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?up:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}dy.NAME="ConstructedValueBlock";class gy extends wp{constructor(e={}){super(e,dy),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}xp=gy,vp.Constructed=xp,gy.NAME="CONSTRUCTED";class fy extends bp{fromBER(e,t,r){return t}toBER(e){return up}}fy.override="EndOfContentValueBlock";class py extends wp{constructor(e={}){super(e,fy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Bp=py,vp.EndOfContent=Bp,py.NAME=gp;class yy extends wp{constructor(e={}){super(e,bp),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}_p=yy,vp.Null=_p,yy.NAME="NULL";class my extends(yp(bp)){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=Tf.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=Tf.toUint8Array(e);return Jf(this,s,t,r)?(this.valueHexView=s.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,jf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}my.NAME="BooleanValueBlock";class by extends wp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,my),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Rp=by,vp.Boolean=Rp,by.NAME="BOOLEAN";class Ay extends(yp(dy)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=dy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===gp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==fp)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,r),this.blockLength=r;return s}toBER(e,t){return this.isConstructed?dy.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Ay.NAME="OctetStringValueBlock";class Iy extends wp{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Ay),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(s.byteLength){const e=ly(s,0,s.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch{}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?gy.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Kf.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Op&&e.push(t.valueBlock.valueHexView);return Tf.concat(e)}}Op=Iy,vp.OctetString=Op,Iy.NAME=fp;class vy extends(yp(dy)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let s=-1;if(this.isConstructed){if(s=dy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===gp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==pp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return s}const i=Tf.toUint8Array(e);if(!Jf(this,i,t,r))return-1;const n=i.subarray(t,t+r);if(this.unusedBits=n[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=n.subarray(1);try{if(e.byteLength){const t=ly(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch{}}return this.valueHexView=n.subarray(1),this.blockLength=n.length,t+r}toBER(e,t){if(this.isConstructed)return dy.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return up;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}vy.NAME="BitStringValueBlock";class wy extends wp{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},vy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return gy.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function Sy(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const o=n.length-1,a=i.slice(0),c=a.length-1;let l=0,h=0;for(let e=c<o?o:c;e>=0;e--,h++)l=1==h<a.length?n[o-h]+a[c-h]+r[0]:n[o-h]+r[0],r[0]=l/10,1==h>=n.length?n=$f(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=$f(r,n)),n}function Ey(e){if(e>=Zf.length)for(let t=Zf.length;t<=e;t++){const e=new Uint8Array([0]);let r=Zf[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const s=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=s[0]/10,r[t]=s[0]%10}e[0]>0&&(r=$f(e,r)),Zf.push(r)}return Zf[e]}function Cy(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),o=n.length-1,a=i.slice(0),c=a.length-1;let l,h=0;for(let e=c;e>=0;e--,h++)l=n[o-h]-a[c-h]-r,1==l<0?(r=1,n[o-h]=l+10):(r=0,n[o-h]=l);if(r>0)for(let e=o-c+1;e>=0;e--,h++){if(l=n[o-h]-r,!(l<0)){r=0,n[o-h]=l;break}r=1,n[o-h]=l+10}return n.slice()}Up=wy,vp.BitString=Up,wy.NAME=pp;class ky extends(yp(bp)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=jf.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let s=1;s<8;s++){if(t<=r){if(e<0){const e=Gf(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=Gf(t,8,s),n=new Uint8Array(i);if(128&n[0]){const e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),n=new Uint8Array(i);for(let r=0;r<e.byteLength;r++)n[r+1]=t[r];n[0]=0}return i}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,s=0){const i=this.fromBER(e,t,r);if(-1===i)return i;const n=this.valueHexView;return 0===n[0]&&128&n[1]?this.valueHexView=n.subarray(1):0!==s&&n.length<s&&(s-n.length>1&&(s=n.length+1),this.valueHexView=n.subarray(s-n.length)),i}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const s=super.fromBER(e,t,r);return-1===s||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),s=0;const i=this.valueHexView;let n="",o=!1;for(let o=i.byteLength-1;o>=0;o--){t=i[o];for(let i=0;i<8;i++)1&~t||(s===e?(r=Cy(Ey(s),r),n="-"):r=Sy(r,Ey(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=Xf.charAt(r[e]));return!1===o&&(n+=Xf.charAt(0)),n}}Tp=ky,ky.NAME="IntegerValueBlock",Object.defineProperty(Tp.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class xy extends wp{constructor(e={}){super(e,ky),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return zf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){zf();const t=BigInt(e),r=new Yf,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Kf.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Kf.ToHex(e)}`)+t,n=Tf.toUint8Array(Kf.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Np({valueHex:r.final()})}convertToDER(){const e=new Np({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Np({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Np=xy,vp.Integer=Np,xy.NAME="INTEGER";class By extends xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Dp=By,vp.Enumerated=Dp,By.NAME="ENUMERATED";class _y extends(yp(bp)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const s=Tf.toUint8Array(e);if(!Jf(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ff(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){zf();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=Gf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",up;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r}toString(){let e="";if(this.isHexOnly)e=Kf.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}_y.NAME="sidBlock";class Ry extends bp{constructor({value:e=hp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new _y;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const s=this.value[r].toBER(e);if(0===s.byteLength)return this.error=this.value[r].error,up;t.push(s)}return Wf(t)}fromString(e){this.value=[];let t=0,r=0,s="",i=!1;do{if(r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1,i){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(s,10);if(isNaN(r))return;e.valueDec=r+t,i=!1}else{const e=new _y;if(s>Number.MAX_SAFE_INTEGER){zf();const t=BigInt(s);e.valueBigInt=t}else if(e.valueDec=parseInt(s,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,this.value[r].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ry.NAME="ObjectIdentifierValueBlock";class Oy extends wp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ry),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Mp=Oy,vp.ObjectIdentifier=Mp,Oy.NAME="OBJECT IDENTIFIER";class Uy extends(yp(mp)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=Tf.toUint8Array(e);if(!Jf(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ff(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=Gf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",up;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r.buffer}toString(){let e="";return e=this.isHexOnly?Kf.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Uy.NAME="relativeSidBlock";class Ty extends bp{constructor({value:e=hp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Uy;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const s=this.value[t].toBER(e);if(0===s.byteLength)return this.error=this.value[t].error,up;r.push(s)}return Wf(r)}fromString(e){this.value=[];let t=0,r=0,s="";do{r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1;const i=new Uy;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ty.NAME="RelativeObjectIdentifierValueBlock";class Ny extends wp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ty),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Pp=Ny,vp.RelativeObjectIdentifier=Pp,Ny.NAME="RelativeObjectIdentifier";class Dy extends gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Lp=Dy,vp.Sequence=Lp,Dy.NAME="SEQUENCE";class My extends gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Hp=My,vp.Set=Hp,My.NAME="SET";class Py extends(yp(bp)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=hp}toJSON(){return{...super.toJSON(),value:this.value}}}Py.NAME="StringValueBlock";class Ly extends Py{}Ly.NAME="SimpleStringValueBlock";class Hy extends Ep{constructor({...e}={}){super(e,Ly)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Tf.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);this.valueBlock.value=e}}Hy.NAME="SIMPLE STRING";class Ky extends Hy{fromBuffer(e){this.valueBlock.valueHexView=Tf.toUint8Array(e);try{this.valueBlock.value=Kf.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Kf.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Kf.FromUtf8String(e)),this.valueBlock.value=e}}Ky.NAME="Utf8StringValueBlock";class Vy extends Ky{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Kp=Vy,vp.Utf8String=Kp,Vy.NAME="UTF8String";class Qy extends Hy{fromBuffer(e){this.valueBlock.value=Kf.ToUtf16String(e),this.valueBlock.valueHexView=Tf.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Kf.FromUtf16String(e))}}Qy.NAME="BmpStringValueBlock";class Fy extends Qy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Vp=Fy,vp.BmpString=Vp,Fy.NAME="BMPString";class Gy extends Hy{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let s=0;s<t;s++){const t=Gf(e.charCodeAt(s),8),i=new Uint8Array(t);if(i.length>4)continue;const n=4-i.length;for(let e=i.length-1;e>=0;e--)r[4*s+e+n]=i[e]}this.valueBlock.value=e}}Gy.NAME="UniversalStringValueBlock";class $y extends Gy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Qp=$y,vp.UniversalString=Qp,$y.NAME="UniversalString";class jy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Fp=jy,vp.NumericString=Fp,jy.NAME="NumericString";class qy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Gp=qy,vp.PrintableString=Gp,qy.NAME="PrintableString";class zy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}$p=zy,vp.TeletexString=$p,zy.NAME="TeletexString";class Wy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}jp=Wy,vp.VideotexString=jp,Wy.NAME="VideotexString";class Jy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}qp=Jy,vp.IA5String=qp,Jy.NAME="IA5String";class Yy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}zp=Yy,vp.GraphicString=zp,Yy.NAME="GraphicString";class Zy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Wp=Zy,vp.VisibleString=Wp,Zy.NAME="VisibleString";class Xy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Jp=Xy,vp.GeneralString=Jp,Xy.NAME="GeneralString";class em extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Yp=em,vp.CharacterString=Yp,em.NAME="CharacterString";class tm extends Zy{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Tf.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=qf(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=qf(this.month,2),e[2]=qf(this.day,2),e[3]=qf(this.hour,2),e[4]=qf(this.minute,2),e[5]=qf(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}Zp=tm,vp.UTCTime=Zp,tm.NAME="UTCTime";class rm extends tm{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t,r=!1,s="",i="",n=0,o=0,a=0;if("Z"===e[e.length-1])s=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(r){if(-1!==s.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==s.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=s.indexOf("+"),r="";if(-1===t&&(t=s.indexOf("-"),e=-1),-1!==t){if(r=s.substring(t+1),s=s.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");a=e*i}}}let c=s.indexOf(".");if(-1===c&&(c=s.indexOf(",")),-1!==c){const e=new Number(`0${s.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");n=e.valueOf(),i=s.substring(0,c)}else i=s;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*n;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(i);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(qf(this.year,4)),e.push(qf(this.month,2)),e.push(qf(this.day,2)),e.push(qf(this.hour,2)),e.push(qf(this.minute,2)),e.push(qf(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(qf(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Xp=rm,vp.GeneralizedTime=Xp,rm.NAME="GeneralizedTime";class sm extends Vy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ey=sm,vp.DATE=ey,sm.NAME="DATE";class im extends Vy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ty=im,vp.TimeOfDay=ty,im.NAME="TimeOfDay";class nm extends Vy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}ry=nm,vp.DateTime=ry,nm.NAME="DateTime";class om extends Vy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}sy=om,vp.Duration=sy,om.NAME="Duration";class am extends Vy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}iy=am,vp.TIME=iy,am.NAME="TIME";class cm{constructor({name:e=hp,optional:t=!1}={}){this.name=e,this.optional=t}}class lm extends cm{constructor({value:e=[],...t}={}){super(t),this.value=e}}class hm extends cm{constructor({value:e=new cm,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class um{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Tf.toUint8Array(e)}constructor({data:e=dp}={}){this.dataView=Tf.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=Tf.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function dm(e,t,r){if(r instanceof lm){for(const s of r.value)if(dm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(ep)&&(e.name=r.name),e}}if(r instanceof cm)return r.hasOwnProperty(ep)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==0)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(sp in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(ap in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(cp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.toBER(!1);if(0===s.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(s,0,s.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty(ip))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(np))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(op))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(rp in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(tp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=t.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:e};for(let t=0;t<s.length;t++)if(s[t]!==i[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&(e[r.name]=t)),r instanceof vp.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof hm&&(n=t.valueBlock.value.length),0===n)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){let t=!0;for(let e=0;e<r.valueBlock.value.length;e++)t=t&&(r.valueBlock.value[e].optional||!1);return t?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let o=0;o<n;o++)if(o-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[o].optional){const t={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof hm){if(i=dm(e,t.valueBlock.value[o],r.valueBlock.value[0].value),!1===i.verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&delete e[r.name]),i;s++}if(ep in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=lp in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e,void 0===s[r.valueBlock.value[0].name]&&(s[r.valueBlock.value[0].name]=[]),s[r.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=dm(e,t.valueBlock.value[o-s],r.valueBlock.value[o]),!1===i.verified){if(!r.valueBlock.value[o].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&delete e[r.name]),i;s++}if(!1===i.verified){const t={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&tp in t.valueBlock){const s=ly(t.valueBlock.valueHexView);if(-1===s.offset){const t={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hp),r.name&&(delete e[r.name],t.name=r.name)),t}return dm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function gm(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=ly(Tf.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:dm(r.result,r.result,t)}(ay=ny||(ny={}))[ay.Sequence=0]="Sequence",ay[ay.Set=1]="Set",ay[ay.Choice=2]="Choice",function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(oy||(oy={}));class fm{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Tf.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Tf.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof wy))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new wy({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new wy({name:e})}toNumber(){let e="";const t=new Uint8Array(this.value);for(const r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2);const r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;const s=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");let i=0;for(;i<r;)s[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=s.buffer}}class pm{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Tf.isBufferSource(e)?this.buffer=Tf.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Iy))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Iy({valueHex:this.buffer})}toSchema(e){return new Iy({name:e})}}const ym={fromASN:e=>e instanceof yy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new yy;const t=hy(e);if(t.result.error)throw new Error(t.result.error);return t.result}},mm={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new xy({value:+e})},bm={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new By({value:e})},Am={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new xy({valueHex:e})},Im={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new wy({valueHex:e})},vm={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Oy({value:e})},wm={fromASN:e=>e.valueBlock.value,toASN:e=>new by({value:e})},Sm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Iy({valueHex:e})},Em={fromASN:e=>new pm(e.getValue()),toASN:e=>e.toASN()};function Cm(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const km=Cm(Vy),xm=Cm(Fy),Bm=Cm($y),_m=Cm(jy),Rm=Cm(qy),Om=Cm(zy),Um=Cm(Wy),Tm=Cm(Jy),Nm=Cm(Yy),Dm=Cm(Zy),Mm=Cm(Xy),Pm=Cm(em),Lm={fromASN:e=>e.toDate(),toASN:e=>new tm({valueDate:e})},Hm={fromASN:e=>e.toDate(),toASN:e=>new rm({valueDate:e})},Km={fromASN:()=>null,toASN:()=>new yy};function Vm(e){switch(e){case oy.Any:return ym;case oy.BitString:return Im;case oy.BmpString:return xm;case oy.Boolean:return wm;case oy.CharacterString:return Pm;case oy.Enumerated:return bm;case oy.GeneralString:return Mm;case oy.GeneralizedTime:return Hm;case oy.GraphicString:return Nm;case oy.IA5String:return Tm;case oy.Integer:return mm;case oy.Null:return Km;case oy.NumericString:return _m;case oy.ObjectIdentifier:return vm;case oy.OctetString:return Sm;case oy.PrintableString:return Rm;case oy.TeletexString:return Om;case oy.UTCTime:return Lm;case oy.UniversalString:return Bm;case oy.Utf8String:return km;case oy.VideotexString:return Um;case oy.VisibleString:return Dm;default:return null}}function Qm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Qm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Fm(e){var t;if(e){const r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||Fm(r)}return!1}function Gm(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}const $m=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){const t={type:ny.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){const r=this.items.get(e)||this.createDefault(e),s=[];for(const e in r.items){const i=r.items[e],n=t?e:"";let o;if("number"==typeof i.type){const e=oy[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else Qm(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===ny.Choice?o=new cm({name:n}):(o=this.create(i.type,!1),o.name=n):o=new cm({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?My:Dy)({name:"",value:[new hm({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Qm(i.type)){const e=i.repeated?gy:cy;s.push(new e({name:n,optional:c,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const e=!!i.repeated;let t=e?o:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new gy({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new gy({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case ny.Sequence:return new Dy({value:s,name:""});case ny.Set:return new My({value:s,name:""});case ny.Choice:return new lm({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},jm=e=>t=>{let r;$m.has(t)?r=$m.get(t):(r=$m.createDefault(t),$m.set(t,r)),Object.assign(r,e)},qm=e=>(t,r)=>{let s;$m.has(t.constructor)?s=$m.get(t.constructor):(s=$m.createDefault(t.constructor),$m.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Vm(e.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);i.converter=s}s.items[r]=i};class zm extends Error{constructor(){super(...arguments),this.schemas=[]}}class Wm{static parse(e,t){const r=hy(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r;try{if(Qm(t))return(new t).fromASN(e);const s=$m.get(t);$m.cache(t);let i=s.schema;if(e.constructor===gy&&s.type!==ny.Choice){i=new gy({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=dm({},e,i);if(!n.verified)throw new zm(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(Fm(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const r=s.itemType;if("number"==typeof r){const s=Vm(r);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,e=>s.fromASN(e))}return t.from(e.valueBlock.value,e=>this.fromASN(e,r))}for(const e in s.items){const t=n.result[e];if(!t)continue;const i=s.items[e],c=i.type;if("number"==typeof c||Qm(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Qm(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?Dy:My);r.valueBlock=t.valueBlock;const n=hy(r.toBER(!1));if(-1===n.offset)throw new Error(`Cannot parse the child item. ${n.result.error}`);if(!("value"in n.result.valueBlock)||!Array.isArray(n.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const a=n.result.valueBlock.value;o[e]=Array.from(a,e=>s.fromASN(e))}else o[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(Qm(c))e=(new c).toSchema("");else{const t=oy[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=hy(e.toBER(!1)).result}o[e]=s.fromASN(r)}}else if(i.repeated){if(!Array.isArray(t))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");o[e]=Array.from(t,e=>this.fromASN(e,c))}else o[e]=this.fromASN(t,c)}return o}catch(e){throw e instanceof zm&&e.schemas.push(t.name),e}}}class Jm{static serialize(e){return e instanceof wp?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Qm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=$m.get(t);$m.cache(t);let s,i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){const s=Vm(r.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);i=e.map(e=>s.toASN(e))}else i=e.map(e=>this.toAsnItem({type:r.itemType},"[]",t,e))}else for(const s in r.items){const n=r.items[s],o=e[s];if(void 0===o||n.defaultValue===o||"object"==typeof n.defaultValue&&"object"==typeof o&&Gm(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=Jm.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Qm(n.type))i.push(new gy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof yy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new cy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new gy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[a]}));else n.repeated?i=i.concat(a):i.push(a)}switch(r.type){case ny.Sequence:s=new Dy({value:i});break;case ny.Set:s=new My({value:i});break;case ny.Choice:if(!i[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);s=i[0]}return s}static toAsnItem(e,t,r,s){let i;if("number"==typeof e.type){const n=e.converter;if(!n)throw new Error(`Property '${t}' doesn't have converter for type ${oy[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>n.toASN(e));i=new("sequence"===e.repeated?Dy:My)({value:t})}else i=n.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>this.toASN(e));i=new("sequence"===e.repeated?Dy:My)({value:t})}else i=this.toASN(s);return i}}class Ym extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Zm{static serialize(e){return Jm.serialize(e)}static parse(e,t){return Wm.parse(e,t)}static toString(e){const t=hy(Tf.isBufferSource(e)?Tf.toArrayBuffer(e):Zm.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Xm(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class eb extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class tb extends eb{constructor(e,t,r){super(t,r),this.schema=e}}class rb extends tb{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class sb extends eb{}class ib extends eb{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class nb extends rb{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var ob;function ab(e,t){if(!function(e,t){switch(t){case ob.Boolean:return"boolean"==typeof e;case ob.Number:return"number"==typeof e;case ob.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${ob[t]}`)}function cb(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||cb(e.prototype):!!(e&&e.toJSON&&e.fromJSON)}!function(e){e[e.Any=0]="Any",e[e.Boolean=1]="Boolean",e[e.Number=2]="Number",e[e.String=3]="String"}(ob||(ob={}));const lb="default",hb=new class{constructor(){this.items=new Map}has(e){return this.items.has(e)||!!this.findParentSchema(e)}get(e){const t=this.items.get(e)||this.findParentSchema(e);if(!t)throw new Error("Cannot get schema for current target");return t}create(e){const t={names:{}},r=this.findParentSchema(e);if(r){Object.assign(t,r),t.names={};for(const e in r.names)t.names[e]=Object.assign({},r.names[e])}return t.target=e,t}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=e.__proto__;return t?this.items.get(t)||this.findParentSchema(t):null}};class ub{constructor(e){this.pattern=new RegExp(e)}validate(e){const t=new RegExp(this.pattern.source,this.pattern.flags);if("string"!=typeof e)throw new sb("Incoming value must be string");if(!t.exec(e))throw new sb(`Value doesn't match to pattern '${t.toString()}'`)}}class db{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(ab(e,ob.Number),!(this.min<=e&&e<=this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new sb(`Value doesn't match to diapason [${e},${t}]`)}}}class gb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(ab(e,ob.Number),!(this.min<e&&e<this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new sb(`Value doesn't match to diapason (${e},${t})`)}}}class fb{constructor(e,t,r){this.length=e,this.minLength=t,this.maxLength=r}validate(e){if(void 0===this.length){if(void 0!==this.minLength&&e.length<this.minLength)throw new sb(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new sb(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new sb(`Value length must be exactly ${this.length}.`)}}class pb{constructor(e){this.enumeration=e}validate(e){if(ab(e,ob.String),!this.enumeration.includes(e))throw new sb(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class yb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof fb&&t.repeated?r.validate(e):r.validate(s)}static checkTypes(e,t){if(t.repeated&&!Array.isArray(e))throw new TypeError("Value must be Array");if("number"==typeof t.type){const r=Array.isArray(e)?e:[e];for(const e of r)ab(e,t.type)}}static getSchemaByName(e,t=lb){return{...e.names[lb],...e.names[t]}}}class mb extends yb{static serialize(e,t,r,s){const i=this.toJSON(e,t);return JSON.stringify(i,r,s)}static toJSON(e,t={}){let r,s=t.targetSchema;const i=t.schemaName||lb;if(cb(e))return e.toJSON();if(Array.isArray(e)){r=[];for(const s of e)r.push(this.toJSON(s,t))}else if("object"==typeof e){if(s&&!hb.has(s))throw new eb("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,hb.has(s)){const t=hb.get(s);r={};const n=this.getSchemaByName(t,i);for(const o in n)try{const t=n[o],a=e[o];let c;if(t.optional&&void 0===a||void 0!==t.defaultValue&&a===t.defaultValue)continue;if(!t.optional&&void 0===a)throw new ib(s.name,`Property '${o}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?a.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(a,e):a:t.repeated?a.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(a,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||o]=c}catch(e){throw e instanceof ib?e:new ib(t.target.name,`Property '${o}' is wrong. ${e.message}`,e)}}else{r={};for(const t in e)r[t]=this.toJSON(e[t],{schemaName:i})}}else r=e;return r}}class bb extends yb{static parse(e,t){const r=JSON.parse(e);return this.fromJSON(r,t)}static fromJSON(e,t){const r=t.targetSchema,s=t.schemaName||lb,i=new r;if(cb(i))return i.fromJSON(e);const n=hb.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&bb.checkStrictProperty(e,o,n);for(const r in o)try{const a=o[r],c=a.name||r,l=e[c];if(void 0===l&&(a.optional||void 0!==a.defaultValue))continue;if(!a.optional&&void 0===l)throw new rb(n,`Property '${c}' is required.`);if(this.checkTypes(l,a),this.checkValues(l,a),"number"==typeof a.type)a.converter?a.repeated?i[r]=l.map(e=>a.converter.fromJSON(e,i)):i[r]=a.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:a.type,schemaName:s};a.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof rb||(e=new rb(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;a[r]=e}const c=Object.keys(a);if(c.length)throw new nb(n,c,a);return i}static checkStrictProperty(e,t,r){const s=Object.keys(e),i=Object.keys(t),n=[];for(const e of s)-1===i.indexOf(e)&&n.push(e);if(n.length)throw new nb(r,n)}}const Ab=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;hb.has(t.constructor)?(i=hb.get(t.constructor),i.target!==t.constructor&&(i=hb.create(t.constructor),hb.set(t.constructor,i))):(i=hb.create(t.constructor),hb.set(t.constructor,i));const n={type:ob.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new ub(e.pattern)),e.type!==ob.Number&&e.type!==ob.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new db(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new gb(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new pb(e.enumeration))),(e.type===ob.String||e.repeated||e.type===ob.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new fb(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!hb.has(o.type)&&!cb(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||lb];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class Ib extends Error{}class vb extends Ib{}class wb extends Ib{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class Sb extends Ib{}class Eb extends Ib{constructor(e){super(`${e}: Missing required property`)}}class Cb{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Kf.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Kf.ToBase64(e);let s,i=0;const n=[];for(;i<r.length&&(s=r.slice(i,i+64),s.length);)n.push(s),i+=64;const o=t.toUpperCase();return`-----BEGIN ${o}-----\n${n.join("\n")}\n-----END ${o}-----`}static isPEM(e){return/-----BEGIN .+-----[A-Za-z0-9+/+=\s\n]+-----END .+-----/i.test(e)}static getTagName(e){if(!this.isPEM(e))throw new Error("Bad parameter. Incoming data is not right PEM");const t=/-----BEGIN (.+)-----/.exec(e);if(!t)throw new Error("Cannot get tag from PEM");return t[1]}static hasTagName(e,t){const r=this.getTagName(e);return t.toLowerCase()===r.toLowerCase()}static isCertificate(e){return this.hasTagName(e,"certificate")}static isCertificateRequest(e){return this.hasTagName(e,"certificate request")}static isCRL(e){return this.hasTagName(e,"x509 crl")}static isPublicKey(e){return this.hasTagName(e,"public key")}}class kb{async digest(...e){return this.checkDigest.apply(this,e),this.onDigest.apply(this,e)}checkDigest(e,t){this.checkAlgorithmName(e)}async onDigest(e,t){throw new wb("digest")}async generateKey(...e){return this.checkGenerateKey.apply(this,e),this.onGenerateKey.apply(this,e)}checkGenerateKey(e,t,r,...s){if(this.checkAlgorithmName(e),this.checkGenerateKeyParams(e),!r||!r.length)throw new TypeError("Usages cannot be empty when creating a key.");let i;i=Array.isArray(this.usages)?this.usages:this.usages.privateKey.concat(this.usages.publicKey),this.checkKeyUsages(r,i)}checkGenerateKeyParams(e){}async onGenerateKey(e,t,r,...s){throw new wb("generateKey")}async sign(...e){return this.checkSign.apply(this,e),this.onSign.apply(this,e)}checkSign(e,t,r,...s){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"sign")}async onSign(e,t,r,...s){throw new wb("sign")}async verify(...e){return this.checkVerify.apply(this,e),this.onVerify.apply(this,e)}checkVerify(e,t,r,s,...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"verify")}async onVerify(e,t,r,s,...i){throw new wb("verify")}async encrypt(...e){return this.checkEncrypt.apply(this,e),this.onEncrypt.apply(this,e)}checkEncrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"encrypt":void 0)}async onEncrypt(e,t,r,...s){throw new wb("encrypt")}async decrypt(...e){return this.checkDecrypt.apply(this,e),this.onDecrypt.apply(this,e)}checkDecrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"decrypt":void 0)}async onDecrypt(e,t,r,...s){throw new wb("decrypt")}async deriveBits(...e){return this.checkDeriveBits.apply(this,e),this.onDeriveBits.apply(this,e)}checkDeriveBits(e,t,r,s={},...i){if(this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"deriveBits":void 0),r%8!=0)throw new Sb("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new wb("deriveBits")}async exportKey(...e){return this.checkExportKey.apply(this,e),this.onExportKey.apply(this,e)}checkExportKey(e,t,...r){if(this.checkKeyFormat(e),this.checkCryptoKey(t),!t.extractable)throw new Ib("key: Is not extractable")}async onExportKey(e,t,...r){throw new wb("exportKey")}async importKey(...e){return this.checkImportKey.apply(this,e),this.onImportKey.apply(this,e)}checkImportKey(e,t,r,s,i,...n){this.checkKeyFormat(e),this.checkKeyData(e,t),this.checkAlgorithmName(r),this.checkImportParams(r),Array.isArray(this.usages)&&this.checkKeyUsages(i,this.usages)}async onImportKey(e,t,r,s,i,...n){throw new wb("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new vb("Unrecognized name")}checkAlgorithmParams(e){}checkDerivedKeyParams(e){}checkKeyUsages(e,t){for(const r of e)if(-1===t.indexOf(r))throw new TypeError("Cannot create a key using the specified key usages")}checkCryptoKey(e,t){if(this.checkAlgorithmName(e.algorithm),t&&-1===e.usages.indexOf(t))throw new Ib("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new Eb(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new Sb(`hash: Must be one of ${t.join(", ")}`)}checkImportParams(e){}checkKeyFormat(e){switch(e){case"raw":case"pkcs8":case"spki":case"jwk":break;default:throw new TypeError("format: Is invalid value. Must be 'jwk', 'raw', 'spki', or 'pkcs8'")}}checkKeyData(e,t){if(!t)throw new TypeError("keyData: Cannot be empty on empty on key importing");if("jwk"===e){if("object"!=typeof(r=t)||!("kty"in r))throw new TypeError("keyData: Is not JsonWebToken")}else if(!Tf.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return Tf.toArrayBuffer(e)}}class xb extends kb{checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");switch(e.length){case 128:case 192:case 256:break;default:throw new TypeError("length: Must be 128, 192, or 256")}}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Bb extends xb{constructor(){super(...arguments),this.name="AES-CBC",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.iv.byteLength)throw new TypeError("iv: Must have length 16 bytes")}}class _b extends xb{constructor(){super(...arguments),this.name="AES-CMAC",this.usages=["sign","verify"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Sb("length: Must be more than 0")}}class Rb extends xb{constructor(){super(...arguments),this.name="AES-CTR",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"counter"),!(e.counter instanceof ArrayBuffer||ArrayBuffer.isView(e.counter)))throw new TypeError("counter: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.counter.byteLength)throw new TypeError("iv: Must have length 16 bytes");if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Sb("length: Must be more than 0")}}class Ob extends xb{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Ub extends xb{constructor(){super(...arguments),this.name="AES-GCM",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){var t;if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength<1)throw new Sb("iv: Must have length more than 0 and less than 2^64 - 1");switch(null!==(t=e.tagLength)&&void 0!==t||(e.tagLength=128),e.tagLength){case 32:case 64:case 96:case 104:case 112:case 120:case 128:break;default:throw new Sb("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class Tb extends xb{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class Nb extends kb{constructor(){super(...arguments),this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.ivSize){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength!==this.ivSize)throw new TypeError(`iv: Must have length ${this.ivSize} bytes`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");if(e.length!==this.keySizeBits)throw new Sb(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Db extends kb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"]}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Kf.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");if(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength%8||e.modulusLength<256||e.modulusLength>16384)throw new TypeError("The modulus length must be a multiple of 8 bits and >= 256 and <= 16384")}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class Mb extends Db{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Pb extends Db{constructor(){super(...arguments),this.name="RSA-PSS",this.usages={privateKey:["sign"],publicKey:["verify"]}}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"saltLength"),"number"!=typeof e.saltLength)throw new TypeError("saltLength: Is not a Number");if(e.saltLength<0)throw new RangeError("saltLength: Must be positive number")}}class Lb extends Db{constructor(){super(...arguments),this.name="RSA-OAEP",this.usages={privateKey:["decrypt","unwrapKey"],publicKey:["encrypt","wrapKey"]}}checkAlgorithmParams(e){if(e.label&&!(e.label instanceof ArrayBuffer||ArrayBuffer.isView(e.label)))throw new TypeError("label: Is not of type '(ArrayBuffer or ArrayBufferView)'")}}class Hb extends kb{checkGenerateKeyParams(e){this.checkRequiredProperty(e,"namedCurve"),this.checkNamedCurve(e.namedCurve)}checkNamedCurve(e){for(const t of this.namedCurves)if(t.toLowerCase()===e.toLowerCase())return;throw new Sb(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Kb extends Hb{constructor(){super(...arguments),this.name="ECDSA",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}const Vb=["secret","private","public"];class Qb{static create(e,t,r,s){const i=new this;return i.algorithm=e,i.type=t,i.extractable=r,i.usages=s,i}static isKeyType(e){return-1!==Vb.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class Fb extends Hb{constructor(){super(...arguments),this.name="ECDH",this.usages={privateKey:["deriveBits","deriveKey"],publicKey:[]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"public"),!(e.public instanceof Qb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new Sb("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new Sb(`public: Is not ${this.name} key`)}}class Gb extends Fb{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class $b extends Hb{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let jb=class{constructor(e){e&&(this.value=e)}};Xm([qm({type:oy.ObjectIdentifier})],jb.prototype,"value",void 0),jb=Xm([jm({type:ny.Choice})],jb);class qb{constructor(e){Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],qb.prototype,"algorithm",void 0),Xm([qm({type:oy.Any,optional:!0})],qb.prototype,"parameters",void 0);class zb{constructor(){this.version=0,this.privateKeyAlgorithm=new qb,this.privateKey=new ArrayBuffer(0)}}Xm([qm({type:oy.Integer})],zb.prototype,"version",void 0),Xm([qm({type:qb})],zb.prototype,"privateKeyAlgorithm",void 0),Xm([qm({type:oy.OctetString})],zb.prototype,"privateKey",void 0),Xm([qm({type:oy.Any,optional:!0})],zb.prototype,"attributes",void 0);class Wb{constructor(){this.publicKeyAlgorithm=new qb,this.publicKey=new ArrayBuffer(0)}}Xm([qm({type:qb})],Wb.prototype,"publicKeyAlgorithm",void 0),Xm([qm({type:oy.BitString})],Wb.prototype,"publicKey",void 0);const Jb={fromJSON:e=>Kf.FromBase64Url(e),toJSON:e=>Kf.ToBase64Url(new Uint8Array(e))},Yb={fromASN:e=>{const t=e.valueBlock.valueHex;return new Uint8Array(t)[0]?e.valueBlock.valueHex:e.valueBlock.valueHex.slice(1)},toASN:e=>{const t=new Uint8Array(e)[0]>127?Vf(new Uint8Array([0]).buffer,e):e;return new xy({valueHex:t})}};class Zb{constructor(){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0)}}Xm([qm({type:oy.Integer,converter:mm})],Zb.prototype,"version",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"n",converter:Jb})],Zb.prototype,"modulus",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"e",converter:Jb})],Zb.prototype,"publicExponent",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"d",converter:Jb})],Zb.prototype,"privateExponent",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"p",converter:Jb})],Zb.prototype,"prime1",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"q",converter:Jb})],Zb.prototype,"prime2",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"dp",converter:Jb})],Zb.prototype,"exponent1",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"dq",converter:Jb})],Zb.prototype,"exponent2",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"qi",converter:Jb})],Zb.prototype,"coefficient",void 0),Xm([qm({type:oy.Any,optional:!0})],Zb.prototype,"otherPrimeInfos",void 0);class Xb{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"n",converter:Jb})],Xb.prototype,"modulus",void 0),Xm([qm({type:oy.Integer,converter:Yb}),Ab({name:"e",converter:Jb})],Xb.prototype,"publicExponent",void 0);let eA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){let e=new Uint8Array(this.value);if(4!==e[0])throw new Ib("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Kf.ToBase64Url(e.buffer.slice(0,0+t)),y:Kf.ToBase64Url(e.buffer.slice(0+t,0+t+t))}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");if(!("y"in e))throw new Error("y: Missing required property");const t=Kf.FromBase64Url(e.x),r=Kf.FromBase64Url(e.y),s=Vf(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Xm([qm({type:oy.OctetString})],eA.prototype,"value",void 0),eA=Xm([jm({type:ny.Choice})],eA);class tA{constructor(){this.version=1,this.privateKey=new ArrayBuffer(0)}fromJSON(e){if(!("d"in e))throw new Error("d: Missing required property");if(this.privateKey=Kf.FromBase64Url(e.d),"x"in e){const t=new eA;t.fromJSON(e);const r=Jm.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Kf.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new eA(this.publicKey).toJSON()),e}}Xm([qm({type:oy.Integer,converter:mm})],tA.prototype,"version",void 0),Xm([qm({type:oy.OctetString})],tA.prototype,"privateKey",void 0),Xm([qm({context:0,type:oy.Any,optional:!0})],tA.prototype,"parameters",void 0),Xm([qm({context:1,type:oy.BitString,optional:!0})],tA.prototype,"publicKey",void 0);const rA={fromASN:e=>{const t=new Uint8Array(e.valueBlock.valueHex);return 0===t[0]?t.buffer.slice(1):t.buffer},toASN:e=>{const t=new Uint8Array(e);if(t[0]>127){const e=new Uint8Array(t.length+1);return e.set(t,1),new xy({valueHex:e.buffer})}return new xy({valueHex:e})}};var sA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:rA});class iA{static decodePoint(e,t){const r=Tf.toUint8Array(e);if(0===r.length||4!==r[0])throw new Error("Only uncompressed point format supported");const s=(r.length-1)/2;if(s!==Math.ceil(t/8))throw new Error("Point does not match field size");return{x:r.slice(1,s+1),y:r.slice(s+1,s+1+s)}}static encodePoint(e,t){const r=Math.ceil(t/8);if(e.x.byteLength!==r||e.y.byteLength!==r)throw new Error("X,Y coordinates don't match point size criteria");const s=Tf.toUint8Array(e.x),i=Tf.toUint8Array(e.y),n=new Uint8Array(2*r+1);return n[0]=4,n.set(s,1),n.set(i,r+1),n}static getSize(e){return Math.ceil(e/8)}static encodeSignature(e,t){const r=this.getSize(t),s=Tf.toUint8Array(e.r),i=Tf.toUint8Array(e.s),n=new Uint8Array(2*r);return n.set(this.padStart(s,r)),n.set(this.padStart(i,r),r),n}static decodeSignature(e,t){const r=this.getSize(t),s=Tf.toUint8Array(e);if(s.length!==2*r)throw new Error("Incorrect size of the signature");const i=s.slice(0,r),n=s.slice(r);return{r:this.trimStart(i),s:this.trimStart(n)}}static trimStart(e){let t=0;for(;t<e.length-1&&0===e[t];)t++;return 0===t?e:e.slice(t,e.length)}static padStart(e,t){if(t===e.length)return e;const r=new Uint8Array(t);return r.set(e,t-e.length),r}}class nA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=iA.decodeSignature(e,8*t),s=new nA;return s.r=Tf.toArrayBuffer(r.r),s.s=Tf.toArrayBuffer(r.s),s}toWebCryptoSignature(e){if(!e){const t=Math.max(this.r.byteLength,this.s.byteLength);e=t<=32?256:t<=48?384:521}return iA.encodeSignature(this,e).buffer}}Xm([qm({type:oy.Integer,converter:rA})],nA.prototype,"r",void 0),Xm([qm({type:oy.Integer,converter:rA})],nA.prototype,"s",void 0);class oA extends zb{}Xm([qm({context:1,implicit:!0,type:oy.BitString,optional:!0})],oA.prototype,"publicKey",void 0);let aA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=Kf.FromBase64Url(e.d),this}toJSON(){return{d:Kf.ToBase64Url(this.value)}}};Xm([qm({type:oy.OctetString})],aA.prototype,"value",void 0),aA=Xm([jm({type:ny.Choice})],aA);let cA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Kf.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Kf.FromBase64Url(e.x),this}};Xm([qm({type:oy.BitString})],cA.prototype,"value",void 0),cA=Xm([jm({type:ny.Choice})],cA);let lA=class{};Xm([qm({type:oy.OctetString}),Ab({type:ob.String,converter:Jb})],lA.prototype,"d",void 0),lA=Xm([jm({type:ny.Choice})],lA);const hA="1.2.840.10045.3.1.7",uA="1.3.132.0",dA=`${uA}.34`,gA=`${uA}.35`,fA=`${uA}.10`,pA="1.3.36.3.3.2.8.1.1",yA=`${pA}.1`,mA=`${pA}.2`,bA=`${pA}.3`,AA=`${pA}.4`,IA=`${pA}.5`,vA=`${pA}.6`,wA=`${pA}.7`,SA=`${pA}.8`,EA=`${pA}.9`,CA=`${pA}.10`,kA=`${pA}.11`,xA=`${pA}.12`,BA=`${pA}.13`,_A=`${pA}.14`;var RA=Object.freeze({__proto__:null,AlgorithmIdentifier:qb,get CurvePrivateKey(){return lA},EcDsaSignature:nA,EcPrivateKey:tA,get EcPublicKey(){return eA},get EdPrivateKey(){return aA},get EdPublicKey(){return cA},get ObjectIdentifier(){return jb},OneAsymmetricKey:oA,PrivateKeyInfo:zb,PublicKeyInfo:Wb,RsaPrivateKey:Zb,RsaPublicKey:Xb,converters:sA,idBrainpoolP160r1:yA,idBrainpoolP160t1:mA,idBrainpoolP192r1:bA,idBrainpoolP192t1:AA,idBrainpoolP224r1:IA,idBrainpoolP224t1:vA,idBrainpoolP256r1:wA,idBrainpoolP256t1:SA,idBrainpoolP320r1:EA,idBrainpoolP320t1:CA,idBrainpoolP384r1:kA,idBrainpoolP384t1:xA,idBrainpoolP512r1:BA,idBrainpoolP512t1:_A,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:uA,idSecp256k1:fA,idSecp256r1:hA,idSecp384r1:dA,idSecp521r1:gA,idVersionOne:pA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class OA{constructor(){}static register(e){const t=new jb;t.value=e.id;const r=Zm.serialize(t);this.items.push({...e,raw:r}),this.names.push(e.name)}static find(e){e=e.toUpperCase();for(const t of this.items)if(t.name.toUpperCase()===e||t.id.toUpperCase()===e)return t;return null}static get(e){const t=this.find(e);if(!t)throw new Error(`Unsupported EC named curve '${e}'`);return t}}OA.items=[],OA.names=[],OA.register({name:"P-256",id:hA,size:256}),OA.register({name:"P-384",id:dA,size:384}),OA.register({name:"P-521",id:gA,size:521}),OA.register({name:"K-256",id:fA,size:256}),OA.register({name:"brainpoolP160r1",id:yA,size:160}),OA.register({name:"brainpoolP160t1",id:mA,size:160}),OA.register({name:"brainpoolP192r1",id:bA,size:192}),OA.register({name:"brainpoolP192t1",id:AA,size:192}),OA.register({name:"brainpoolP224r1",id:IA,size:224}),OA.register({name:"brainpoolP224t1",id:vA,size:224}),OA.register({name:"brainpoolP256r1",id:wA,size:256}),OA.register({name:"brainpoolP256t1",id:SA,size:256}),OA.register({name:"brainpoolP320r1",id:EA,size:320}),OA.register({name:"brainpoolP320t1",id:CA,size:320}),OA.register({name:"brainpoolP384r1",id:kA,size:384}),OA.register({name:"brainpoolP384t1",id:xA,size:384}),OA.register({name:"brainpoolP512r1",id:BA,size:512}),OA.register({name:"brainpoolP512t1",id:_A,size:512});class UA extends kb{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class TA extends kb{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class NA extends kb{constructor(){super(...arguments),this.name="HMAC",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["sign","verify"]}getDefaultLength(e){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":return 512;default:throw new Error(`Unknown algorithm name '${e}'`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),"length"in e){if("number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new RangeError("length: Number is out of range")}}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class DA extends kb{constructor(){super(...arguments),this.name="PBKDF2",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveBits","deriveKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!(e.salt instanceof ArrayBuffer||ArrayBuffer.isView(e.salt)))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"iterations"),"number"!=typeof e.iterations)throw new TypeError("iterations: Is not a Number");if(e.iterations<1)throw new TypeError("iterations: Is less than 1")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class MA extends kb{constructor(){super(...arguments),this.name="HKDF",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveKey","deriveBits"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!Tf.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!Tf.isBufferSource(e.info))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class PA extends kb{constructor(){super(...arguments),this.usages=[],this.defaultLength=0}digest(...e){return e[0]={length:this.defaultLength,...e[0]},super.digest.apply(this,e)}checkDigest(e,t){super.checkDigest(e,t);const r=e.length||0;if("number"!=typeof r)throw new TypeError("length: Is not a Number");if(r<0)throw new TypeError("length: Is negative")}}class LA extends PA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class HA extends PA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class KA{get[Symbol.toStringTag](){return"Crypto"}randomUUID(){const e=this.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Kf.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class VA{constructor(){this.items={}}get(e){return this.items[e.toLowerCase()]||null}set(e){this.items[e.name.toLowerCase()]=e}removeAt(e){const t=this.get(e.toLowerCase());return t&&delete this.items[e],t}has(e){return!!this.get(e)}get length(){return Object.keys(this.items).length}get algorithms(){const e=[];for(const t in this.items){const r=this.items[t];e.push(r.name)}return e.sort()}}const QA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},FA=["pkcs8","spki","raw"];class GA{constructor(){this.providers=new VA}static isHashedAlgorithm(e){return!!(e&&"object"==typeof e&&"name"in e&&"hash"in e)}get[Symbol.toStringTag](){return"SubtleCrypto"}async digest(...e){this.checkRequiredArguments(e,2,"digest");const[t,r,...s]=e,i=this.prepareAlgorithm(t),n=Tf.toArrayBuffer(r),o=this.getProvider(i.name);return await o.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.generateKey({...n,name:o.name},r,s,...i)}async sign(...e){this.checkRequiredArguments(e,3,"sign");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.sign({...n,name:a.name},r,o,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const o=this.prepareAlgorithm(t),a=Tf.toArrayBuffer(i),c=Tf.toArrayBuffer(s),l=this.getProvider(o.name);return await l.verify({...o,name:l.name},r,c,a,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.encrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async decrypt(...e){this.checkRequiredArguments(e,3,"decrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.decrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async deriveBits(...e){this.checkRequiredArguments(e,3,"deriveBits");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.deriveBits({...n,name:o.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s);this.getProvider(a.name).checkDerivedKeyParams(a);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const h=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...o);return this.importKey("raw",h,s,i,n,...o)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!QA[t])throw new TypeError("Invalid keyFormat argument");if(!QA[t].includes(r.type))throw new DOMException("The key is not of the expected type");const i=this.getProvider(r.algorithm.name);return await i.exportKey(t,r,...s)}async importKey(...e){this.checkRequiredArguments(e,5,"importKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s),c=this.getProvider(a.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!FA.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!Tf.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...a,name:c.name},i,n,...o)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=Kf.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=Tf.toArrayBuffer(n),c=this.getProvider(o.name);return c.encrypt({...o,name:c.name},r,a,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,o,...a){const c=this.prepareAlgorithm(s),l=Tf.toArrayBuffer(t),h=this.getProvider(c.name);let u=await h.decrypt({...c,name:h.name},r,l,{keyUsage:!1},...a);if("jwk"===e)try{u=JSON.parse(Kf.ToUtf8String(u))}catch(e){const t=new TypeError("wrappedKey: Is not a JSON");throw t.internal=e,t}return this.importKey(e,u,i,n,o,...a)}checkRequiredArguments(e,t,r){if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'SubtleCrypto': ${t} arguments required, but only ${e.length} present`)}prepareAlgorithm(e){if("string"==typeof e)return{name:e};if(GA.isHashedAlgorithm(e)){const t={...e};return t.hash=this.prepareAlgorithm(e.hash),t}return{...e}}getProvider(e){const t=this.providers.get(e);if(!t)throw new vb("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Qb))throw new TypeError("Key is not of type 'CryptoKey'")}}const $A=t(import.meta.url)("buffer"),jA=t(import.meta.url)("crypto");var qA=o.n(jA);const zA=t(import.meta.url)("process"),WA={fromJSON:e=>$A.Buffer.from(Kf.FromBase64Url(e)),toJSON:e=>Kf.ToBase64Url(e)};class JA extends Qb{constructor(){super(...arguments),this.data=$A.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Xm([Ab({name:"ext",type:ob.Boolean,optional:!0})],JA.prototype,"extractable",void 0),Xm([Ab({name:"key_ops",type:ob.String,repeated:!0,optional:!0})],JA.prototype,"usages",void 0),Xm([Ab({type:ob.String})],JA.prototype,"kty",void 0),Xm([Ab({type:ob.String,optional:!0})],JA.prototype,"alg",void 0);class YA extends JA{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class ZA extends JA{}class XA extends YA{get alg(){switch(this.algorithm.name.toUpperCase()){case"AES-CBC":return`A${this.algorithm.length}CBC`;case"AES-CTR":return`A${this.algorithm.length}CTR`;case"AES-GCM":return`A${this.algorithm.length}GCM`;case"AES-KW":return`A${this.algorithm.length}KW`;case"AES-CMAC":return`A${this.algorithm.length}CMAC`;case"AES-ECB":return`A${this.algorithm.length}ECB`;default:throw new vb("Unsupported algorithm name")}}set alg(e){}}Xm([Ab({name:"k",converter:WA})],XA.prototype,"data",void 0);class eI{static async generateKey(e,t,r){const s=new XA;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=qA().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof XA))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:XA});break;case"raw":n=new XA,n.data=$A.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}switch(n.algorithm=r,n.algorithm.length=n.data.length<<3,n.extractable=s,n.usages=i,n.algorithm.length){case 128:case 192:case 256:break;default:throw new Sb("keyData: Is wrong key length")}return n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"AES-CBC":return this.encryptAesCBC(e,t,$A.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,$A.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,$A.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,$A.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,$A.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof XA))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,$A.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,$A.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,$A.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,$A.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,$A.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,$A.Buffer.from(e.counter));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,$A.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD($A.Buffer.from(e.additionalData));let i=s.update(r);return i=$A.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=qA().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),o=r.slice(r.length-s);e.additionalData&&i.setAAD($A.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=$A.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=qA().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=qA().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}eI.AES_KW_IV=$A.Buffer.from("A6A6A6A6A6A6A6A6","hex");const tI=new WeakMap;function rI(e){const t=tI.get(e);if(!t)throw new Sb("Cannot get CryptoKey from secure storage");return t}function sI(e){const t=Qb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),tI.set(t,e),t}class iI extends Bb{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return eI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return eI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}const nI=$A.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),oI=$A.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),aI=16;function cI(e){const t=$A.Buffer.alloc(e.length),r=e.length-1;for(let s=0;s<r;s++)t[s]=e[s]<<1,128&e[s+1]&&(t[s]+=1);return t[r]=e[r]<<1,t}function lI(e,t){const r=Math.min(e.length,t.length),s=$A.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function hI(e,t){const r=qA().createCipheriv("aes"+(e.length<<3),e,nI),s=r.update(t);return r.final(),s}function uI(e,t){const r=$A.Buffer.alloc(aI),s=t*aI,i=s+aI;return e.copy(r,0,s,i),r}class dI extends _b{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onSign(e,t,r){const s=function(e,t){const r=function(e){const t=hI(e,nI);let r=cI(t);128&t[0]&&(r=lI(r,oI));let s=cI(r);return 128&r[0]&&(s=lI(s,oI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/aI);0===n?(n=1,s=!1):s=t.length%aI===0;const o=n-1;i=s?lI(uI(t,o),r.subkey1):lI(function(e,t){const r=$A.Buffer.alloc(aI),s=t*aI,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,o),r.subkey2);let a,c=nI;for(let r=0;r<o;r++)a=lI(c,uI(t,r)),c=hI(e,a);return a=lI(i,c),hI(e,a)}(rI(t).data,$A.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===$A.Buffer.from(r).compare($A.Buffer.from(i))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class gI extends Rb{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return eI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return eI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class fI extends Ub{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return eI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return eI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class pI extends Tb{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return eI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return eI.decrypt(e,rI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class yI extends Ob{async onGenerateKey(e,t,r){return sI(await eI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return eI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return eI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return eI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await eI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class mI extends YA{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new vb("Unsupported algorithm name")}}set alg(e){}}Xm([Ab({name:"k",converter:WA})],mI.prototype,"data",void 0);class bI{static async generateKey(e,t,r){const s=new mI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=qA().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:mI});break;case"raw":n=new mI,n.data=$A.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}return n.algorithm=r,n.extractable=s,n.usages=i,n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"DES-CBC":return this.encryptDesCBC(e,t,$A.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,$A.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof mI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,$A.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,$A.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=qA().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=qA().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=qA().createCipheriv("des-ede3-cbc",t.data,$A.Buffer.from(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=qA().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=$A.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class AI extends Nb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return sI(await bI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return bI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return bI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return bI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){const n=await bI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Sb("keyData: Wrong key size");return sI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof mI))throw new TypeError("key: Is not a DesCryptoKey")}}class II extends Nb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return sI(await bI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return bI.encrypt(e,rI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return bI.decrypt(e,rI(t),new Uint8Array(r))}async onExportKey(e,t){return bI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){const n=await bI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Sb("keyData: Wrong key size");return sI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof mI))throw new TypeError("key: Is not a DesCryptoKey")}}function vI(e){switch(e.name.toUpperCase()){case"RSA-OAEP":{const t=/(\d+)$/.exec(e.hash.name)[1];return"RSA-OAEP"+("1"!==t?`-${t}`:"")}case"RSASSA-PKCS1-V1_5":return`RS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PSS":return`PS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PKCS1":return"RS1";default:throw new Sb("algorithm: Is not recognized")}}class wI extends ZA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:vI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){const t=bb.fromJSON(e,{targetSchema:RA.RsaPrivateKey}),r=new RA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=Jm.serialize(t),this.data=$A.Buffer.from(Jm.serialize(r))}}class SI extends ZA{constructor(){super(...arguments),this.type="public"}getKey(){const e=Wm.parse(this.data,RA.PublicKeyInfo);return Wm.parse(e.publicKey,RA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:vI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){const t=bb.fromJSON(e,{targetSchema:RA.RsaPublicKey}),r=new RA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=Jm.serialize(t),this.data=$A.Buffer.from(Jm.serialize(r))}}class EI{static async generateKey(e,t,r){const s=new wI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new SI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=$A.Buffer.concat([$A.Buffer.alloc(4-e.publicExponent.byteLength,0),$A.Buffer.from(e.publicExponent)]).readInt32BE(0),o=qA().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=bb.fromJSON(t,{targetSchema:RA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=bb.fromJSON(t,{targetSchema:RA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo),n=Wm.parse(e.publicKey,RA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async sign(e,t,r){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.signRsa(e,t,r);default:throw new Sb("algorithm: Is not recognized")}}static async verify(e,t,r,s){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.verifySSA(e,t,s,r);default:throw new Sb("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new Sb("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new Sb("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new RA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=Jm.serialize(e);const n=new wI;return n.data=$A.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static importPublicKey(e,t,r,s){const i=new RA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=Jm.serialize(e);const n=new SI;return n.data=$A.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static getCryptoAlgorithm(e){switch(e.hash.name.toUpperCase()){case"SHA-1":return"RSA-SHA1";case"SHA-256":return"RSA-SHA256";case"SHA-384":return"RSA-SHA384";case"SHA-512":return"RSA-SHA512";case"SHA3-256":return"RSA-SHA3-256";case"SHA3-384":return"RSA-SHA3-384";case"SHA3-512":return"RSA-SHA3-512";default:throw new Sb("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=qA().createSign(s);i.update($A.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem};"RSA-PSS"===e.name.toUpperCase()&&(n.padding=qA().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const o=i.sign(n);return new Uint8Array(o).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=qA().createVerify(i);n.update($A.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(o.padding=qA().constants.RSA_PKCS1_PSS_PADDING,o.saltLength=e.saltLength),n.verify(o,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:qA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(qA().publicEncrypt(s,r)).buffer}static decryptOAEP(e,t,r){const s={key:`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`,padding:qA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(qA().privateDecrypt(s,r)).buffer}}EI.publicKeyUsages=["verify","encrypt","wrapKey"],EI.privateKeyUsages=["sign","decrypt","unwrapKey"];class CI extends Mb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await EI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onSign(e,t,r){return EI.sign(e,rI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return EI.verify(e,rI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return EI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await EI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof wI||r instanceof SI))throw new TypeError("key: Is not RSA CryptoKey")}}class kI extends Pb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await EI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onSign(e,t,r){return EI.sign(e,rI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return EI.verify(e,rI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return EI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await EI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof wI||r instanceof SI))throw new TypeError("key: Is not RSA CryptoKey")}}class xI{static size(e){switch(e.name.toUpperCase()){case"SHA-1":return 160;case"SHA-256":case"SHA3-256":return 256;case"SHA-384":case"SHA3-384":return 384;case"SHA-512":case"SHA3-512":return 512;default:throw new Error("Unrecognized name")}}static getAlgorithmName(e){switch(e.name.toUpperCase()){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512";case"SHA3-256":return"sha3-256";case"SHA3-384":return"sha3-384";case"SHA3-512":return"sha3-512";default:throw new Error("Unrecognized name")}}static digest(e,t){const r=this.getAlgorithmName(e),s=qA().createHash(r).update($A.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class BI extends Lb{async onGenerateKey(e,t,r){const s=await EI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onEncrypt(e,t,r){const s=rI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=xI.size(s.algorithm.hash)>>3,a=i.byteLength,c=n-a-2*o-2;if(a>n-2*o-2)throw new Error("Data too large");const l=new Uint8Array(n),h=l.subarray(1,o+1),u=l.subarray(o+1);u.set(i,o+c+1);const d=qA().createHash(s.algorithm.hash.name.replace("-","")).update(Tf.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,qA().randomFillSync(h);const g=this.mgf1(s.algorithm.hash,h,u.length);for(let e=0;e<u.length;e++)u[e]^=g[e];const f=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=f[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=qA().publicEncrypt({key:s.pem,padding:qA().constants.RSA_NO_PADDING},$A.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=rI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=xI.size(s.algorithm.hash)>>3;if(r.byteLength!==i)throw new Error("Bad data");s.pem||(s.pem=`-----BEGIN PRIVATE KEY-----\n${s.data.toString("base64")}\n-----END PRIVATE KEY-----`);let o=qA().privateDecrypt({key:s.pem,padding:qA().constants.RSA_NO_PADDING},$A.Buffer.from(r));const a=o[0],c=o.subarray(1,n+1),l=o.subarray(n+1);if(0!==a)throw new Error("Decryption failed");const h=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=h[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const d=qA().createHash(s.algorithm.hash.name.replace("-","")).update(Tf.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(d[e]!==l[e])throw new Error("Decryption failed");let g=n;for(;g<l.length;g++){const e=l[g];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(g===l.length)throw new Error("Decryption failed");return o=l.subarray(g+1),new Uint8Array(o).buffer}async onExportKey(e,t){return EI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await EI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof wI||r instanceof SI))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=xI.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),o=Math.ceil(r/s);for(let r=0;r<o;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const o=i.subarray(r*s);let a=qA().createHash(e.name.replace("-","")).update(t).update(n).digest();a.length>o.length&&(a=a.subarray(0,o.length)),o.set(a)}return i}}class _I extends kb{constructor(){super(...arguments),this.name="RSAES-PKCS1-v1_5",this.usages={publicKey:["encrypt","wrapKey"],privateKey:["decrypt","unwrapKey"]}}async onGenerateKey(e,t,r){const s=await EI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Kf.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");switch(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength){case 1024:case 2048:case 4096:break;default:throw new TypeError("modulusLength: Must be 1024, 2048, or 4096")}}async onEncrypt(e,t,r){const s=this.toCryptoOptions(t),i=qA().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=qA().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return EI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await EI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof wI||r instanceof SI))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${rI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:qA().constants.RSA_PKCS1_PADDING}}}const RI={"1.2.840.10045.3.1.7":"P-256","P-256":"1.2.840.10045.3.1.7","1.3.132.0.34":"P-384","P-384":"1.3.132.0.34","1.3.132.0.35":"P-521","P-521":"1.3.132.0.35","1.3.132.0.10":"K-256","K-256":"1.3.132.0.10",brainpoolP160r1:"1.3.36.3.3.2.8.1.1.1","1.3.36.3.3.2.8.1.1.1":"brainpoolP160r1",brainpoolP160t1:"1.3.36.3.3.2.8.1.1.2","1.3.36.3.3.2.8.1.1.2":"brainpoolP160t1",brainpoolP192r1:"1.3.36.3.3.2.8.1.1.3","1.3.36.3.3.2.8.1.1.3":"brainpoolP192r1",brainpoolP192t1:"1.3.36.3.3.2.8.1.1.4","1.3.36.3.3.2.8.1.1.4":"brainpoolP192t1",brainpoolP224r1:"1.3.36.3.3.2.8.1.1.5","1.3.36.3.3.2.8.1.1.5":"brainpoolP224r1",brainpoolP224t1:"1.3.36.3.3.2.8.1.1.6","1.3.36.3.3.2.8.1.1.6":"brainpoolP224t1",brainpoolP256r1:"1.3.36.3.3.2.8.1.1.7","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1",brainpoolP256t1:"1.3.36.3.3.2.8.1.1.8","1.3.36.3.3.2.8.1.1.8":"brainpoolP256t1",brainpoolP320r1:"1.3.36.3.3.2.8.1.1.9","1.3.36.3.3.2.8.1.1.9":"brainpoolP320r1",brainpoolP320t1:"1.3.36.3.3.2.8.1.1.10","1.3.36.3.3.2.8.1.1.10":"brainpoolP320t1",brainpoolP384r1:"1.3.36.3.3.2.8.1.1.11","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1",brainpoolP384t1:"1.3.36.3.3.2.8.1.1.12","1.3.36.3.3.2.8.1.1.12":"brainpoolP384t1",brainpoolP512r1:"1.3.36.3.3.2.8.1.1.13","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1",brainpoolP512t1:"1.3.36.3.3.2.8.1.1.14","1.3.36.3.3.2.8.1.1.14":"brainpoolP512t1"};function OI(e){const t=RI[e];if(!t)throw new Sb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class UI extends ZA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=new RA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(OI(e.crv)));const r=bb.fromJSON(e,{targetSchema:RA.EcPrivateKey});return t.privateKey=Jm.serialize(r),this.data=$A.Buffer.from(Jm.serialize(t)),this}}class TI extends ZA{constructor(){super(...arguments),this.type="public"}getKey(){const e=Wm.parse(this.data,RA.PublicKeyInfo);return new RA.EcPublicKey(e.publicKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=bb.fromJSON(e,{targetSchema:RA.EcPublicKey}),r=new RA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(OI(e.crv))),r.publicKey=Jm.toASN(t).valueHex,this.data=$A.Buffer.from(Jm.serialize(r)),this}}class NI extends kb{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class DI extends kb{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class MI extends kb{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class PI extends kb{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class LI extends kb{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class HI extends kb{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class KI extends kb{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return xI.digest(e,t)}}class VI{static async generateKey(e,t,r){const s=new UI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new TI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=qA().generateKeyPairSync("ec",{namedCurve:this.getOpenSSLNamedCurve(e.namedCurve),publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=n.privateKey,i.data=n.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){const s=xI.getAlgorithmName(e.hash),i=qA().createSign(s);i.update($A.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},o=i.sign(n),a=Wm.parse(o,RA.EcDsaSignature);return iA.encodeSignature(a,OA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=xI.getAlgorithmName(e.hash),n=qA().createVerify(i);n.update($A.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem},a=new RA.EcDsaSignature,c=OA.get(t.algorithm.namedCurve),l=iA.decodeSignature(r,c.size);a.r=Tf.toArrayBuffer(l.r),a.s=Tf.toArrayBuffer(l.s);const h=$A.Buffer.from(Jm.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=qA().createECDH(s),n=Wm.parse(t.data,RA.PrivateKeyInfo),o=Wm.parse(n.privateKey,RA.EcPrivateKey);i.setPrivateKey($A.Buffer.from(o.privateKey));const a=Wm.parse(e.public.data,RA.PublicKeyInfo),c=i.computeSecret($A.Buffer.from(a.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Wm.parse(t.data,RA.PublicKeyInfo).publicKey;default:throw new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=bb.fromJSON(t,{targetSchema:RA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=bb.fromJSON(t,{targetSchema:RA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new RA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo),n=new RA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Ib("Key info doesn't have required parameters");let r="";try{r=Wm.parse(e,RA.ObjectIdentifier).value}catch(e){throw new Ib("Cannot read key info parameters")}if(OI(t)!==r)throw new Ib("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new RA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(OI(t.namedCurve))),i.privateKey=Jm.serialize(e);const n=new UI;return n.data=$A.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new RA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=OI(t.namedCurve);i.publicKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new TI;return o.data=$A.Buffer.from(Jm.serialize(i)),o.algorithm=Object.assign({},t),o.extractable=r,o.usages=s,o}static getOpenSSLNamedCurve(e){switch(e.toUpperCase()){case"P-256":return"prime256v1";case"K-256":return"secp256k1";case"P-384":return"secp384r1";case"P-521":return"secp521r1";default:return e}}}VI.publicKeyUsages=["verify"],VI.privateKeyUsages=["sign","deriveKey","deriveBits"];class QI extends Kb{constructor(){super(...arguments),this.namedCurves=OA.names,this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await VI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onSign(e,t,r){return VI.sign(e,rI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return VI.verify(e,rI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return VI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await VI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not EC CryptoKey")}}class FI extends Fb{constructor(){super(...arguments),this.namedCurves=OA.names}async onGenerateKey(e,t,r){const s=await VI.generateKey({...e,name:this.name},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onExportKey(e,t){return VI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await VI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=rI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await VI.deriveBits({...e,public:rI(e.public)},rI(t),r)}}const GI={[RA.idEd448]:"Ed448",ed448:RA.idEd448,[RA.idX448]:"X448",x448:RA.idX448,[RA.idEd25519]:"Ed25519",ed25519:RA.idEd25519,[RA.idX25519]:"X25519",x25519:RA.idX25519};function $I(e){const t=GI[e.toLowerCase()];if(!t)throw new Sb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class jI extends ZA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=new RA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=$I(e.crv);const r=bb.fromJSON(e,{targetSchema:RA.CurvePrivateKey});return t.privateKey=Jm.serialize(r),this.data=$A.Buffer.from(Jm.serialize(t)),this}}class qI extends ZA{constructor(){super(...arguments),this.type="public"}getKey(){return Wm.parse(this.data,RA.PublicKeyInfo).publicKey}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,{x:Kf.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new Sb("Cannot get property from JWK. Property 'x' is required");const t=new RA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=$I(e.crv),t.publicKey=Kf.FromBase64Url(e.x),this.data=$A.Buffer.from(Jm.serialize(t)),this}}class zI{static async generateKey(e,t,r){const s=new jI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new qI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=qA().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const s={key:t.pem},i=qA().sign(null,$A.Buffer.from(r),s);return Tf.toArrayBuffer(i)}static async verify(e,t,r,s){t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const i={key:t.pem};return qA().verify(null,$A.Buffer.from(s),i,$A.Buffer.from(r))}static async deriveBits(e,t,r){const s=qA().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=qA().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=qA().diffieHellman({publicKey:s,privateKey:i});return new Uint8Array(n).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Wm.parse(t.data,RA.PublicKeyInfo).publicKey;default:throw new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":{const e=t;if(e.d){const e=bb.fromJSON(t,{targetSchema:RA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Kf.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new jI;return i.fromJSON({crv:t.namedCurve,d:Kf.ToBase64Url(e.d)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}static async importPublicKey(e,t,r,s){const i=new qI;return i.fromJSON({crv:t.namedCurve,x:Kf.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}zI.publicKeyUsages=["verify"],zI.privateKeyUsages=["sign","deriveKey","deriveBits"];class WI extends $b{async onGenerateKey(e,t,r){const s=await zI.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onSign(e,t,r){return zI.sign(e,rI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return zI.verify(e,rI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return zI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await zI.importKey(e,t,{...r,name:this.name},s,i))}}class JI extends Gb{async onGenerateKey(e,t,r){const s=await zI.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onDeriveBits(e,t,r){return await zI.deriveBits({...e,public:rI(e.public)},rI(t),r)}async onExportKey(e,t){return zI.exportKey(e,rI(t))}async onImportKey(e,t,r,s,i){return sI(await zI.importKey(e,t,{...r,name:this.name},s,i))}}class YI extends JA{constructor(e,t,r,s){super(),this.algorithm=e,this.extractable=t,this.usages=r,this.data=Buffer.from(s)}toJWK(){return{kty:"OKP",crv:this.algorithm.name,key_ops:this.usages,ext:this.extractable}}}class ZI extends YI{constructor(){super(...arguments),this.type="private"}toJWK(){const e=qA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Cb.toUint8Array(this.data.toString()),r=Zm.parse(t,RA.PrivateKeyInfo),s=Zm.parse(r.privateKey,RA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class XI extends YI{constructor(){super(...arguments),this.type="public"}toJWK(){const e=qA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class ev{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=qA().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},o=r.filter(e=>this.privateKeyUsages.includes(e)),a=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new ZI(n,t,o,i.privateKey),publicKey:new XI(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=qA().sign(null,Buffer.from(r),t.data);return Tf.toArrayBuffer(s)}static async verify(e,t,r,s){return qA().verify(null,Buffer.from(s),t.data,r)}static async exportKey(e,t){switch(e){case"jwk":return t.toJWK();case"pkcs8":case"spki":return Cb.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Kf.FromBase64Url(e.x)}default:return Promise.reject(new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}static async importKey(e,t,r,s,i){switch(e){case"jwk":{const e=t;if(e.d){const t=new RA.EdPrivateKey;t.value=Tf.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new RA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?RA.idEd25519:RA.idX25519,n.privateKey=Zm.serialize(t);const o=Zm.serialize(n),a=Cb.fromBufferSource(o,"PRIVATE KEY");return new ZI(r,s,i,a)}if(e.x){const t=qA().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new XI(r,s,i,t)}throw new Sb("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Cb.fromBufferSource(t,"PRIVATE KEY");return new ZI(r,s,i,e)}case"spki":{const e=Cb.fromBufferSource(t,"PUBLIC KEY");return new XI(r,s,i,e)}case"raw":{const e=t,n=qA().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Kf.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new XI(r,s,i,n)}default:return Promise.reject(new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}ev.privateKeyUsages=["sign","deriveBits","deriveKey"],ev.publicKeyUsages=["verify"];class tv extends TA{async onGenerateKey(e,t,r){const s=await ev.generateKey(e,t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onSign(e,t,r){const s=rI(t);return ev.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=rI(t);return ev.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=rI(t);return ev.exportKey(e,r)}async onImportKey(e,t,r,s,i){return sI(await ev.importKey(e,t,r,s,i))}}class rv extends UA{async onGenerateKey(e,t,r){const s=await ev.generateKey(e,t,r);return{privateKey:sI(s.privateKey),publicKey:sI(s.publicKey)}}async onDeriveBits(e,t,r){const s=rI(t),i=rI(e.public),n=qA().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=qA().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=qA().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=rI(t);return ev.exportKey(e,r)}async onImportKey(e,t,r,s,i){return sI(await ev.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof YI))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class sv extends JA{}class iv extends DA{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=Tf.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");qA().pbkdf2(rI(t).data,$A.Buffer.from(n),e.iterations,r>>3,o,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new sv;return e.data=$A.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,sI(e)}throw new Sb("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof sv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class nv extends JA{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Xm([Ab({name:"k",converter:WA})],nv.prototype,"data",void 0);class ov extends NA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new nv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=qA().randomBytes(s>>3),sI(i)}async onSign(e,t,r){const s=xI.getAlgorithmName(t.algorithm.hash),i=qA().createHmac(s,rI(t).data).update($A.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=xI.getAlgorithmName(t.algorithm.hash);return 0===qA().createHmac(i,rI(t).data).update($A.Buffer.from(s)).digest().compare($A.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:nv});break;case"raw":n=new nv,n.data=$A.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}return n.algorithm={hash:{name:r.hash.name},name:this.name,length:n.data.length<<3},n.extractable=s,n.usages=i,sI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(rI(t));case"raw":return new Uint8Array(rI(t).data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof nv))throw new TypeError("key: Is not HMAC CryptoKey")}}class av extends JA{}class cv extends MA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new Sb("Operation not supported");const n=new av;return n.data=$A.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,sI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=qA().createHash(s).digest().length,n=r/8,o=Tf.toUint8Array(e.info),a=qA().createHmac(s,Tf.toUint8Array(e.salt)).update(Tf.toUint8Array(rI(t).data)).digest(),c=[$A.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(qA().createHmac(s,a).update($A.Buffer.concat([c[e-1],o,$A.Buffer.from([e])])).digest());return $A.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(rI(e)instanceof av))throw new TypeError("key: Is not HKDF CryptoKey")}}class lv{static digest(e,t){const r=qA().createHash(e.name.toLowerCase(),{outputLength:e.length}).update($A.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class hv extends LA{async onDigest(e,t){return lv.digest(e,t)}}class uv extends HA{async onDigest(e,t){return lv.digest(e,t)}}class dv extends GA{constructor(){var e;super(),this.providers.set(new iI),this.providers.set(new gI),this.providers.set(new fI),this.providers.set(new dI),this.providers.set(new pI),this.providers.set(new yI),qA().getCiphers().includes("des-cbc")&&this.providers.set(new AI),this.providers.set(new II),this.providers.set(new CI),this.providers.set(new kI),this.providers.set(new BI),this.providers.set(new _I),this.providers.set(new QI),this.providers.set(new FI),this.providers.set(new NI),this.providers.set(new DI),this.providers.set(new MI),this.providers.set(new PI),this.providers.set(new iv),this.providers.set(new ov),this.providers.set(new cv);const t=null===(e=/^v(\d+)/.exec(zA.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new hv),this.providers.set(new uv));const r=qA().getHashes();r.includes("sha3-256")&&this.providers.set(new LI),r.includes("sha3-384")&&this.providers.set(new HI),r.includes("sha3-512")&&this.providers.set(new KI),t&&parseInt(t,10)>=14&&(this.providers.set(new WI),this.providers.set(new JI),this.providers.set(new tv),this.providers.set(new rv))}}var gv,fv,pv;o(909);class yv{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map(e=>{const t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t})}static parseIPv6(e){const t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce((e,t)=>{const r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e},[])}static expandIPv6(e){if(!e.includes("::"))return e;const t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");const r=t[0]?t[0].split(":"):[],s=t[1]?t[1].split(":"):[],i=8-(r.length+s.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...s].join(":")}static formatIPv6(e){const t=[];for(let r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){const t=e.split(":");let r=-1,s=0,i=-1,n=0;for(let e=0;e<t.length;e++)"0"===t[e]?(-1===i&&(i=e),n++):(n>s&&(r=i,s=n),i=-1,n=0);return n>s&&(r=i,s=n),s>1?`${t.slice(0,r).join(":")}::${t.slice(r+s).join(":")}`:e}static parseCIDR(e){const[t,r]=e.split("/"),s=parseInt(r,10);if(this.isIPv4(t)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),s]}if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),s]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;const t=parseInt(e.slice(8),16).toString(2).split("").reduce((e,t)=>e+ +t,0);let r=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return r=r.slice(0,-1),`${r}/${t}`}static toString(e){const t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){const e=t.length/2,r=t.slice(0,e),s=t.slice(e);if(t.every(e=>0===e))return 8===t.length?"0.0.0.0/0":"::/0";const i=s.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return 8===t.length?`${Array.from(r).join(".")}/${i}`:`${this.formatIPv6(r)}/${i}`}return this.decodeIP(Kf.ToHex(e))}static fromString(e){if(e.includes("/")){const[t,r]=this.parseCIDR(e),s=new Uint8Array(t.length);let i=r;for(let e=0;e<s.length;e++)i>=8?(s[e]=255,i-=8):i>0&&(s[e]=255<<8-i,i=0);const n=new Uint8Array(2*t.length);return n.set(t,0),n.set(s,t.length),n.buffer}const t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}let mv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Xm([qm({type:oy.TeletexString})],mv.prototype,"teletexString",void 0),Xm([qm({type:oy.PrintableString})],mv.prototype,"printableString",void 0),Xm([qm({type:oy.UniversalString})],mv.prototype,"universalString",void 0),Xm([qm({type:oy.Utf8String})],mv.prototype,"utf8String",void 0),Xm([qm({type:oy.BmpString})],mv.prototype,"bmpString",void 0),mv=Xm([jm({type:ny.Choice})],mv);let bv=class extends mv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Kf.ToHex(this.anyValue):super.toString())}};Xm([qm({type:oy.IA5String})],bv.prototype,"ia5String",void 0),Xm([qm({type:oy.Any})],bv.prototype,"anyValue",void 0),bv=Xm([jm({type:ny.Choice})],bv);class Av{constructor(e={}){this.type="",this.value=new bv,Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Av.prototype,"type",void 0),Xm([qm({type:bv})],Av.prototype,"value",void 0);let Iv=gv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,gv.prototype)}};Iv=gv=Xm([jm({type:ny.Set,itemType:Av})],Iv);let vv=fv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,fv.prototype)}};vv=fv=Xm([jm({type:ny.Sequence,itemType:Iv})],vv);let wv=pv=class extends vv{constructor(e){super(e),Object.setPrototypeOf(this,pv.prototype)}};wv=pv=Xm([jm({type:ny.Sequence})],wv);const Sv={fromASN:e=>yv.toString(Sm.fromASN(e)),toASN:e=>Sm.toASN(yv.fromString(e))};class Ev{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Ev.prototype,"typeId",void 0),Xm([qm({type:oy.Any,context:0})],Ev.prototype,"value",void 0);class Cv{constructor(e={}){this.partyName=new mv,Object.assign(this,e)}}Xm([qm({type:mv,optional:!0,context:0,implicit:!0})],Cv.prototype,"nameAssigner",void 0),Xm([qm({type:mv,context:1,implicit:!0})],Cv.prototype,"partyName",void 0);let kv=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:Ev,context:0,implicit:!0})],kv.prototype,"otherName",void 0),Xm([qm({type:oy.IA5String,context:1,implicit:!0})],kv.prototype,"rfc822Name",void 0),Xm([qm({type:oy.IA5String,context:2,implicit:!0})],kv.prototype,"dNSName",void 0),Xm([qm({type:oy.Any,context:3,implicit:!0})],kv.prototype,"x400Address",void 0),Xm([qm({type:wv,context:4,implicit:!1})],kv.prototype,"directoryName",void 0),Xm([qm({type:Cv,context:5})],kv.prototype,"ediPartyName",void 0),Xm([qm({type:oy.IA5String,context:6,implicit:!0})],kv.prototype,"uniformResourceIdentifier",void 0),Xm([qm({type:oy.OctetString,context:7,implicit:!0,converter:Sv})],kv.prototype,"iPAddress",void 0),Xm([qm({type:oy.ObjectIdentifier,context:8,implicit:!0})],kv.prototype,"registeredID",void 0),kv=Xm([jm({type:ny.Choice})],kv);const xv="1.3.6.1.5.5.7",Bv=`${xv}.3`,_v=`${xv}.48`,Rv=`${_v}.1`,Ov=`${_v}.2`,Uv=`${_v}.3`,Tv=`${_v}.5`,Nv="2.5.29";var Dv;const Mv=`${xv}.1.1`;class Pv{constructor(e={}){this.accessMethod="",this.accessLocation=new kv,Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Pv.prototype,"accessMethod",void 0),Xm([qm({type:kv})],Pv.prototype,"accessLocation",void 0);let Lv=Dv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Dv.prototype)}};Lv=Dv=Xm([jm({type:ny.Sequence,itemType:Pv})],Lv);const Hv=`${Nv}.35`;class Kv extends pm{}class Vv{constructor(e={}){e&&Object.assign(this,e)}}Xm([qm({type:Kv,context:0,optional:!0,implicit:!0})],Vv.prototype,"keyIdentifier",void 0),Xm([qm({type:kv,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Vv.prototype,"authorityCertIssuer",void 0),Xm([qm({type:oy.Integer,context:2,optional:!0,implicit:!0,converter:Am})],Vv.prototype,"authorityCertSerialNumber",void 0);const Qv=`${Nv}.19`;class Fv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Gv;Xm([qm({type:oy.Boolean,defaultValue:!1})],Fv.prototype,"cA",void 0),Xm([qm({type:oy.Integer,optional:!0})],Fv.prototype,"pathLenConstraint",void 0);let $v=Gv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Gv.prototype)}};var jv;$v=Gv=Xm([jm({type:ny.Sequence,itemType:kv})],$v);let qv=jv=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,jv.prototype)}};var zv;qv=jv=Xm([jm({type:ny.Sequence})],qv);const Wv=`${Nv}.32`;let Jv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Xm([qm({type:oy.IA5String})],Jv.prototype,"ia5String",void 0),Xm([qm({type:oy.VisibleString})],Jv.prototype,"visibleString",void 0),Xm([qm({type:oy.BmpString})],Jv.prototype,"bmpString",void 0),Xm([qm({type:oy.Utf8String})],Jv.prototype,"utf8String",void 0),Jv=Xm([jm({type:ny.Choice})],Jv);class Yv{constructor(e={}){this.organization=new Jv,this.noticeNumbers=[],Object.assign(this,e)}}Xm([qm({type:Jv})],Yv.prototype,"organization",void 0),Xm([qm({type:oy.Integer,repeated:"sequence"})],Yv.prototype,"noticeNumbers",void 0);class Zv{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:Yv,optional:!0})],Zv.prototype,"noticeRef",void 0),Xm([qm({type:Jv,optional:!0})],Zv.prototype,"explicitText",void 0);let Xv=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:oy.IA5String})],Xv.prototype,"cPSuri",void 0),Xm([qm({type:Zv})],Xv.prototype,"userNotice",void 0),Xv=Xm([jm({type:ny.Choice})],Xv);class ew{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],ew.prototype,"policyQualifierId",void 0),Xm([qm({type:oy.Any})],ew.prototype,"qualifier",void 0);class tw{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],tw.prototype,"policyIdentifier",void 0),Xm([qm({type:ew,repeated:"sequence",optional:!0})],tw.prototype,"policyQualifiers",void 0);let rw=zv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,zv.prototype)}};rw=zv=Xm([jm({type:ny.Sequence,itemType:tw})],rw);let sw=class{constructor(e=0){this.value=e}};Xm([qm({type:oy.Integer})],sw.prototype,"value",void 0),sw=Xm([jm({type:ny.Choice})],sw);let iw=class extends sw{};var nw;iw=Xm([jm({type:ny.Choice})],iw);const ow=`${Nv}.31`;var aw;!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(aw||(aw={}));class cw extends fm{toJSON(){const e=[],t=this.toNumber();return t&aw.aACompromise&&e.push("aACompromise"),t&aw.affiliationChanged&&e.push("affiliationChanged"),t&aw.cACompromise&&e.push("cACompromise"),t&aw.certificateHold&&e.push("certificateHold"),t&aw.cessationOfOperation&&e.push("cessationOfOperation"),t&aw.keyCompromise&&e.push("keyCompromise"),t&aw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&aw.superseded&&e.push("superseded"),t&aw.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let lw=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:kv,context:0,repeated:"sequence",implicit:!0})],lw.prototype,"fullName",void 0),Xm([qm({type:Iv,context:1,implicit:!0})],lw.prototype,"nameRelativeToCRLIssuer",void 0),lw=Xm([jm({type:ny.Choice})],lw);class hw{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:lw,context:0,optional:!0})],hw.prototype,"distributionPoint",void 0),Xm([qm({type:cw,context:1,optional:!0,implicit:!0})],hw.prototype,"reasons",void 0),Xm([qm({type:kv,context:2,optional:!0,repeated:"sequence",implicit:!0})],hw.prototype,"cRLIssuer",void 0);let uw=nw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,nw.prototype)}};var dw;uw=nw=Xm([jm({type:ny.Sequence,itemType:hw})],uw);let gw=dw=class extends uw{constructor(e){super(e),Object.setPrototypeOf(this,dw.prototype)}};gw=dw=Xm([jm({type:ny.Sequence,itemType:hw})],gw);class fw{constructor(e={}){this.onlyContainsUserCerts=fw.ONLY,this.onlyContainsCACerts=fw.ONLY,this.indirectCRL=fw.ONLY,this.onlyContainsAttributeCerts=fw.ONLY,Object.assign(this,e)}}var pw;fw.ONLY=!1,Xm([qm({type:lw,context:0,optional:!0})],fw.prototype,"distributionPoint",void 0),Xm([qm({type:oy.Boolean,context:1,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsUserCerts",void 0),Xm([qm({type:oy.Boolean,context:2,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsCACerts",void 0),Xm([qm({type:cw,context:3,optional:!0,implicit:!0})],fw.prototype,"onlySomeReasons",void 0),Xm([qm({type:oy.Boolean,context:4,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"indirectCRL",void 0),Xm([qm({type:oy.Boolean,context:5,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(pw||(pw={}));let yw=class{constructor(e=pw.unspecified){this.reason=pw.unspecified,this.reason=e}toJSON(){return pw[this.reason]}toString(){return this.toJSON()}};var mw;Xm([qm({type:oy.Enumerated})],yw.prototype,"reason",void 0),yw=Xm([jm({type:ny.Choice})],yw);const bw=`${Nv}.37`;let Aw=mw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,mw.prototype)}};Aw=mw=Xm([jm({type:ny.Sequence,itemType:oy.ObjectIdentifier})],Aw);const Iw=`${Bv}.1`,vw=`${Bv}.2`,ww=`${Bv}.3`,Sw=`${Bv}.4`,Ew=`${Bv}.8`,Cw=`${Bv}.9`;let kw=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Xm([qm({type:oy.Integer,converter:Am})],kw.prototype,"value",void 0),kw=Xm([jm({type:ny.Choice})],kw);let xw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var Bw;Xm([qm({type:oy.GeneralizedTime})],xw.prototype,"value",void 0),xw=Xm([jm({type:ny.Choice})],xw);let _w=Bw=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,Bw.prototype)}};_w=Bw=Xm([jm({type:ny.Sequence})],_w);const Rw=`${Nv}.15`;var Ow,Uw;!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Ow||(Ow={}));class Tw extends fm{toJSON(){const e=this.toNumber(),t=[];return e&Ow.cRLSign&&t.push("crlSign"),e&Ow.dataEncipherment&&t.push("dataEncipherment"),e&Ow.decipherOnly&&t.push("decipherOnly"),e&Ow.digitalSignature&&t.push("digitalSignature"),e&Ow.encipherOnly&&t.push("encipherOnly"),e&Ow.keyAgreement&&t.push("keyAgreement"),e&Ow.keyCertSign&&t.push("keyCertSign"),e&Ow.keyEncipherment&&t.push("keyEncipherment"),e&Ow.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class Nw{constructor(e={}){this.base=new kv,this.minimum=0,Object.assign(this,e)}}Xm([qm({type:kv})],Nw.prototype,"base",void 0),Xm([qm({type:oy.Integer,context:0,defaultValue:0,implicit:!0})],Nw.prototype,"minimum",void 0),Xm([qm({type:oy.Integer,context:1,optional:!0,implicit:!0})],Nw.prototype,"maximum",void 0);let Dw=Uw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Uw.prototype)}};Dw=Uw=Xm([jm({type:ny.Sequence,itemType:Nw})],Dw);class Mw{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:Dw,context:0,optional:!0,implicit:!0})],Mw.prototype,"permittedSubtrees",void 0),Xm([qm({type:Dw,context:1,optional:!0,implicit:!0})],Mw.prototype,"excludedSubtrees",void 0);class Pw{constructor(e={}){Object.assign(this,e)}}var Lw;Xm([qm({type:oy.Integer,context:0,implicit:!0,optional:!0,converter:Am})],Pw.prototype,"requireExplicitPolicy",void 0),Xm([qm({type:oy.Integer,context:1,implicit:!0,optional:!0,converter:Am})],Pw.prototype,"inhibitPolicyMapping",void 0);class Hw{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Hw.prototype,"issuerDomainPolicy",void 0),Xm([qm({type:oy.ObjectIdentifier})],Hw.prototype,"subjectDomainPolicy",void 0);let Kw=Lw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Lw.prototype)}};var Vw;Kw=Lw=Xm([jm({type:ny.Sequence,itemType:Hw})],Kw);const Qw=`${Nv}.17`;let Fw=Vw=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,Vw.prototype)}};Fw=Vw=Xm([jm({type:ny.Sequence})],Fw);class Gw{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var $w;Xm([qm({type:oy.ObjectIdentifier})],Gw.prototype,"type",void 0),Xm([qm({type:oy.Any,repeated:"set"})],Gw.prototype,"values",void 0);let jw=$w=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,$w.prototype)}};jw=$w=Xm([jm({type:ny.Sequence,itemType:Gw})],jw);const qw=`${Nv}.14`;class zw extends Kv{}class Ww{constructor(e={}){Object.assign(this,e)}}var Jw,Yw;Xm([qm({type:oy.GeneralizedTime,context:0,implicit:!0,optional:!0})],Ww.prototype,"notBefore",void 0),Xm([qm({type:oy.GeneralizedTime,context:1,implicit:!0,optional:!0})],Ww.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Jw||(Jw={}));class Zw extends fm{toJSON(){const e=[],t=this.toNumber();return t&Jw.pKIXCertificate&&e.push("pKIXCertificate"),t&Jw.newExtensions&&e.push("newExtensions"),t&Jw.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Xw{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Zw,Object.assign(this,e)}}Xm([qm({type:oy.GeneralString})],Xw.prototype,"entrustVers",void 0),Xm([qm({type:Zw})],Xw.prototype,"entrustInfoFlags",void 0);let eS=Yw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Yw.prototype)}};eS=Yw=Xm([jm({type:ny.Sequence,itemType:Pv})],eS);class tS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof tS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Qf(e.parameters,this.parameters)||e.parameters===this.parameters)}}Xm([qm({type:oy.ObjectIdentifier})],tS.prototype,"algorithm",void 0),Xm([qm({type:oy.Any,optional:!0})],tS.prototype,"parameters",void 0);class rS{constructor(e={}){this.algorithm=new tS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:tS})],rS.prototype,"algorithm",void 0),Xm([qm({type:oy.BitString})],rS.prototype,"subjectPublicKey",void 0);let sS=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){const t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};Xm([qm({type:oy.UTCTime})],sS.prototype,"utcTime",void 0),Xm([qm({type:oy.GeneralizedTime})],sS.prototype,"generalTime",void 0),sS=Xm([jm({type:ny.Choice})],sS);class iS{constructor(e){this.notBefore=new sS(new Date),this.notAfter=new sS(new Date),e&&(this.notBefore=new sS(e.notBefore),this.notAfter=new sS(e.notAfter))}}var nS;Xm([qm({type:sS})],iS.prototype,"notBefore",void 0),Xm([qm({type:sS})],iS.prototype,"notAfter",void 0);class oS{constructor(e={}){this.extnID="",this.critical=oS.CRITICAL,this.extnValue=new pm,Object.assign(this,e)}}oS.CRITICAL=!1,Xm([qm({type:oy.ObjectIdentifier})],oS.prototype,"extnID",void 0),Xm([qm({type:oy.Boolean,defaultValue:oS.CRITICAL})],oS.prototype,"critical",void 0),Xm([qm({type:pm})],oS.prototype,"extnValue",void 0);let aS=nS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,nS.prototype)}};var cS;aS=nS=Xm([jm({type:ny.Sequence,itemType:oS})],aS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(cS||(cS={}));class lS{constructor(e={}){this.version=cS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new tS,this.issuer=new wv,this.validity=new iS,this.subject=new wv,this.subjectPublicKeyInfo=new rS,Object.assign(this,e)}}Xm([qm({type:oy.Integer,context:0,defaultValue:cS.v1})],lS.prototype,"version",void 0),Xm([qm({type:oy.Integer,converter:Am})],lS.prototype,"serialNumber",void 0),Xm([qm({type:tS})],lS.prototype,"signature",void 0),Xm([qm({type:wv})],lS.prototype,"issuer",void 0),Xm([qm({type:iS})],lS.prototype,"validity",void 0),Xm([qm({type:wv})],lS.prototype,"subject",void 0),Xm([qm({type:rS})],lS.prototype,"subjectPublicKeyInfo",void 0),Xm([qm({type:oy.BitString,context:1,implicit:!0,optional:!0})],lS.prototype,"issuerUniqueID",void 0),Xm([qm({type:oy.BitString,context:2,implicit:!0,optional:!0})],lS.prototype,"subjectUniqueID",void 0),Xm([qm({type:aS,context:3,optional:!0})],lS.prototype,"extensions",void 0);class hS{constructor(e={}){this.tbsCertificate=new lS,this.signatureAlgorithm=new tS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:lS})],hS.prototype,"tbsCertificate",void 0),Xm([qm({type:tS})],hS.prototype,"signatureAlgorithm",void 0),Xm([qm({type:oy.BitString})],hS.prototype,"signatureValue",void 0);class uS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new sS,Object.assign(this,e)}}Xm([qm({type:oy.Integer,converter:Am})],uS.prototype,"userCertificate",void 0),Xm([qm({type:sS})],uS.prototype,"revocationDate",void 0),Xm([qm({type:oS,optional:!0,repeated:"sequence"})],uS.prototype,"crlEntryExtensions",void 0);class dS{constructor(e={}){this.signature=new tS,this.issuer=new wv,this.thisUpdate=new sS,Object.assign(this,e)}}Xm([qm({type:oy.Integer,optional:!0})],dS.prototype,"version",void 0),Xm([qm({type:tS})],dS.prototype,"signature",void 0),Xm([qm({type:wv})],dS.prototype,"issuer",void 0),Xm([qm({type:sS})],dS.prototype,"thisUpdate",void 0),Xm([qm({type:sS,optional:!0})],dS.prototype,"nextUpdate",void 0),Xm([qm({type:uS,repeated:"sequence",optional:!0})],dS.prototype,"revokedCertificates",void 0),Xm([qm({type:oS,optional:!0,context:0,repeated:"sequence"})],dS.prototype,"crlExtensions",void 0);class gS{constructor(e={}){this.tbsCertList=new dS,this.signatureAlgorithm=new tS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:dS})],gS.prototype,"tbsCertList",void 0),Xm([qm({type:tS})],gS.prototype,"signatureAlgorithm",void 0),Xm([qm({type:oy.BitString})],gS.prototype,"signature",void 0);class fS{constructor(e={}){this.issuer=new wv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:wv})],fS.prototype,"issuer",void 0),Xm([qm({type:oy.Integer,converter:Am})],fS.prototype,"serialNumber",void 0);let pS=class{constructor(e={}){Object.assign(this,e)}};var yS;Xm([qm({type:zw,context:0,implicit:!0})],pS.prototype,"subjectKeyIdentifier",void 0),Xm([qm({type:fS})],pS.prototype,"issuerAndSerialNumber",void 0),pS=Xm([jm({type:ny.Choice})],pS),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(yS||(yS={}));let mS=class extends tS{};mS=Xm([jm({type:ny.Sequence})],mS);let bS=class extends tS{};bS=Xm([jm({type:ny.Sequence})],bS);let AS=class extends tS{};AS=Xm([jm({type:ny.Sequence})],AS);let IS=class extends tS{};IS=Xm([jm({type:ny.Sequence})],IS);let vS=class extends tS{};vS=Xm([jm({type:ny.Sequence})],vS);let wS=class extends tS{};wS=Xm([jm({type:ny.Sequence})],wS);class SS{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var ES;Xm([qm({type:oy.ObjectIdentifier})],SS.prototype,"attrType",void 0),Xm([qm({type:oy.Any,repeated:"set"})],SS.prototype,"attrValues",void 0);class CS{constructor(e={}){this.version=yS.v0,this.sid=new pS,this.digestAlgorithm=new mS,this.signatureAlgorithm=new bS,this.signature=new pm,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],CS.prototype,"version",void 0),Xm([qm({type:pS})],CS.prototype,"sid",void 0),Xm([qm({type:mS})],CS.prototype,"digestAlgorithm",void 0),Xm([qm({type:SS,repeated:"set",context:0,implicit:!0,optional:!0})],CS.prototype,"signedAttrs",void 0),Xm([qm({type:bS})],CS.prototype,"signatureAlgorithm",void 0),Xm([qm({type:pm})],CS.prototype,"signature",void 0),Xm([qm({type:SS,repeated:"set",context:1,implicit:!0,optional:!0})],CS.prototype,"unsignedAttrs",void 0);let kS=ES=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,ES.prototype)}};kS=ES=Xm([jm({type:ny.Set,itemType:CS})],kS);let xS=class extends sS{};xS=Xm([jm({type:ny.Choice})],xS);let BS=class extends CS{};BS=Xm([jm({type:ny.Sequence})],BS);class _S{constructor(e={}){this.acIssuer=new kv,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var RS;Xm([qm({type:kv})],_S.prototype,"acIssuer",void 0),Xm([qm({type:oy.Integer})],_S.prototype,"acSerial",void 0),Xm([qm({type:Gw,repeated:"sequence"})],_S.prototype,"attrs",void 0);let OS=RS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,RS.prototype)}};OS=RS=Xm([jm({type:ny.Sequence,itemType:oy.ObjectIdentifier})],OS);class US{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Xm([qm({type:oy.Integer,optional:!0})],US.prototype,"pathLenConstraint",void 0),Xm([qm({type:OS,implicit:!0,context:0,optional:!0})],US.prototype,"permittedAttrs",void 0),Xm([qm({type:OS,implicit:!0,context:1,optional:!0})],US.prototype,"excludedAttrs",void 0),Xm([qm({type:oy.Boolean,defaultValue:!0})],US.prototype,"permitUnSpecified",void 0);class TS{constructor(e={}){this.issuer=new $v,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var NS;Xm([qm({type:$v})],TS.prototype,"issuer",void 0),Xm([qm({type:oy.Integer,converter:Am})],TS.prototype,"serial",void 0),Xm([qm({type:oy.BitString,optional:!0})],TS.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(NS||(NS={}));class DS{constructor(e={}){this.digestedObjectType=NS.publicKey,this.digestAlgorithm=new tS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.Enumerated})],DS.prototype,"digestedObjectType",void 0),Xm([qm({type:oy.ObjectIdentifier,optional:!0})],DS.prototype,"otherObjectTypeID",void 0),Xm([qm({type:tS})],DS.prototype,"digestAlgorithm",void 0),Xm([qm({type:oy.BitString})],DS.prototype,"objectDigest",void 0);class MS{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:$v,optional:!0})],MS.prototype,"issuerName",void 0),Xm([qm({type:TS,context:0,implicit:!0,optional:!0})],MS.prototype,"baseCertificateID",void 0),Xm([qm({type:DS,context:1,implicit:!0,optional:!0})],MS.prototype,"objectDigestInfo",void 0);let PS=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:kv,repeated:"sequence"})],PS.prototype,"v1Form",void 0),Xm([qm({type:MS,context:0,implicit:!0})],PS.prototype,"v2Form",void 0),PS=Xm([jm({type:ny.Choice})],PS);class LS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Xm([qm({type:oy.GeneralizedTime})],LS.prototype,"notBeforeTime",void 0),Xm([qm({type:oy.GeneralizedTime})],LS.prototype,"notAfterTime",void 0);class HS{constructor(e={}){Object.assign(this,e)}}var KS,VS,QS;Xm([qm({type:TS,implicit:!0,context:0,optional:!0})],HS.prototype,"baseCertificateID",void 0),Xm([qm({type:$v,implicit:!0,context:1,optional:!0})],HS.prototype,"entityName",void 0),Xm([qm({type:DS,implicit:!0,context:2,optional:!0})],HS.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(KS||(KS={}));class FS{constructor(e={}){this.version=KS.v2,this.holder=new HS,this.issuer=new PS,this.signature=new tS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new LS,this.attributes=[],Object.assign(this,e)}}Xm([qm({type:oy.Integer})],FS.prototype,"version",void 0),Xm([qm({type:HS})],FS.prototype,"holder",void 0),Xm([qm({type:PS})],FS.prototype,"issuer",void 0),Xm([qm({type:tS})],FS.prototype,"signature",void 0),Xm([qm({type:oy.Integer,converter:Am})],FS.prototype,"serialNumber",void 0),Xm([qm({type:LS})],FS.prototype,"attrCertValidityPeriod",void 0),Xm([qm({type:Gw,repeated:"sequence"})],FS.prototype,"attributes",void 0),Xm([qm({type:oy.BitString,optional:!0})],FS.prototype,"issuerUniqueID",void 0),Xm([qm({type:aS,optional:!0})],FS.prototype,"extensions",void 0);class GS{constructor(e={}){this.acinfo=new FS,this.signatureAlgorithm=new tS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:FS})],GS.prototype,"acinfo",void 0),Xm([qm({type:tS})],GS.prototype,"signatureAlgorithm",void 0),Xm([qm({type:oy.BitString})],GS.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(VS||(VS={}));class $S extends fm{}class jS{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier,implicit:!0,context:0})],jS.prototype,"type",void 0),Xm([qm({type:oy.Any,implicit:!0,context:1})],jS.prototype,"value",void 0);class qS{constructor(e={}){this.policyId="",this.classList=new $S(VS.unclassified),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],qS.prototype,"policyId",void 0),Xm([qm({type:$S,defaultValue:new $S(VS.unclassified)})],qS.prototype,"classList",void 0),Xm([qm({type:jS,repeated:"set"})],qS.prototype,"securityCategories",void 0);class zS{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:pm})],zS.prototype,"cotets",void 0),Xm([qm({type:oy.ObjectIdentifier})],zS.prototype,"oid",void 0),Xm([qm({type:oy.Utf8String})],zS.prototype,"string",void 0);class WS{constructor(e={}){this.values=[],Object.assign(this,e)}}Xm([qm({type:$v,implicit:!0,context:0,optional:!0})],WS.prototype,"policyAuthority",void 0),Xm([qm({type:zS,repeated:"sequence"})],WS.prototype,"values",void 0);class JS{constructor(e={}){this.targetCertificate=new TS,Object.assign(this,e)}}Xm([qm({type:TS})],JS.prototype,"targetCertificate",void 0),Xm([qm({type:kv,optional:!0})],JS.prototype,"targetName",void 0),Xm([qm({type:DS,optional:!0})],JS.prototype,"certDigestInfo",void 0);let YS=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:kv,context:0,implicit:!0})],YS.prototype,"targetName",void 0),Xm([qm({type:kv,context:1,implicit:!0})],YS.prototype,"targetGroup",void 0),Xm([qm({type:JS,context:2,implicit:!0})],YS.prototype,"targetCert",void 0),YS=Xm([jm({type:ny.Choice})],YS);let ZS=QS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,QS.prototype)}};var XS;ZS=QS=Xm([jm({type:ny.Sequence,itemType:YS})],ZS);let eE=XS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,XS.prototype)}};eE=XS=Xm([jm({type:ny.Sequence,itemType:ZS})],eE);class tE{constructor(e={}){Object.assign(this,e)}}Xm([qm({type:$v,implicit:!0,context:0,optional:!0})],tE.prototype,"roleAuthority",void 0),Xm([qm({type:kv,implicit:!0,context:1})],tE.prototype,"roleName",void 0);class rE{constructor(e={}){this.service=new kv,this.ident=new kv,Object.assign(this,e)}}var sE;Xm([qm({type:kv})],rE.prototype,"service",void 0),Xm([qm({type:kv})],rE.prototype,"ident",void 0),Xm([qm({type:pm,optional:!0})],rE.prototype,"authInfo",void 0);class iE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],iE.prototype,"otherCertFormat",void 0),Xm([qm({type:oy.Any})],iE.prototype,"otherCert",void 0);let nE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:hS})],nE.prototype,"certificate",void 0),Xm([qm({type:GS,context:2,implicit:!0})],nE.prototype,"v2AttrCert",void 0),Xm([qm({type:iE,context:3,implicit:!0})],nE.prototype,"other",void 0),nE=Xm([jm({type:ny.Choice})],nE);let oE=sE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,sE.prototype)}};oE=sE=Xm([jm({type:ny.Set,itemType:nE})],oE);class aE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],aE.prototype,"contentType",void 0),Xm([qm({type:oy.Any,context:0})],aE.prototype,"content",void 0);let cE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:pm})],cE.prototype,"single",void 0),Xm([qm({type:oy.Any})],cE.prototype,"any",void 0),cE=Xm([jm({type:ny.Choice})],cE);class lE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],lE.prototype,"eContentType",void 0),Xm([qm({type:cE,context:0,optional:!0})],lE.prototype,"eContent",void 0);let hE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:pm,context:0,implicit:!0,optional:!0})],hE.prototype,"value",void 0),Xm([qm({type:pm,converter:Em,context:0,implicit:!0,optional:!0,repeated:"sequence"})],hE.prototype,"constructedValue",void 0),hE=Xm([jm({type:ny.Choice})],hE);class uE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new IS,Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],uE.prototype,"contentType",void 0),Xm([qm({type:IS})],uE.prototype,"contentEncryptionAlgorithm",void 0),Xm([qm({type:hE,optional:!0})],uE.prototype,"encryptedContent",void 0);class dE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var gE;Xm([qm({type:oy.ObjectIdentifier})],dE.prototype,"keyAttrId",void 0),Xm([qm({type:oy.Any,optional:!0})],dE.prototype,"keyAttr",void 0);class fE{constructor(e={}){this.subjectKeyIdentifier=new zw,Object.assign(this,e)}}Xm([qm({type:zw})],fE.prototype,"subjectKeyIdentifier",void 0),Xm([qm({type:oy.GeneralizedTime,optional:!0})],fE.prototype,"date",void 0),Xm([qm({type:dE,optional:!0})],fE.prototype,"other",void 0);let pE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:fE,context:0,implicit:!0,optional:!0})],pE.prototype,"rKeyId",void 0),Xm([qm({type:fS,optional:!0})],pE.prototype,"issuerAndSerialNumber",void 0),pE=Xm([jm({type:ny.Choice})],pE);class yE{constructor(e={}){this.rid=new pE,this.encryptedKey=new pm,Object.assign(this,e)}}Xm([qm({type:pE})],yE.prototype,"rid",void 0),Xm([qm({type:pm})],yE.prototype,"encryptedKey",void 0);let mE=gE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,gE.prototype)}};mE=gE=Xm([jm({type:ny.Sequence,itemType:yE})],mE);class bE{constructor(e={}){this.algorithm=new tS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:tS})],bE.prototype,"algorithm",void 0),Xm([qm({type:oy.BitString})],bE.prototype,"publicKey",void 0);let AE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:zw,context:0,implicit:!0,optional:!0})],AE.prototype,"subjectKeyIdentifier",void 0),Xm([qm({type:bE,context:1,implicit:!0,optional:!0})],AE.prototype,"originatorKey",void 0),Xm([qm({type:fS,optional:!0})],AE.prototype,"issuerAndSerialNumber",void 0),AE=Xm([jm({type:ny.Choice})],AE);class IE{constructor(e={}){this.version=yS.v3,this.originator=new AE,this.keyEncryptionAlgorithm=new AS,this.recipientEncryptedKeys=new mE,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],IE.prototype,"version",void 0),Xm([qm({type:AE,context:0})],IE.prototype,"originator",void 0),Xm([qm({type:pm,context:1,optional:!0})],IE.prototype,"ukm",void 0),Xm([qm({type:AS})],IE.prototype,"keyEncryptionAlgorithm",void 0),Xm([qm({type:mE})],IE.prototype,"recipientEncryptedKeys",void 0);let vE=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:zw,context:0,implicit:!0})],vE.prototype,"subjectKeyIdentifier",void 0),Xm([qm({type:fS})],vE.prototype,"issuerAndSerialNumber",void 0),vE=Xm([jm({type:ny.Choice})],vE);class wE{constructor(e={}){this.version=yS.v0,this.rid=new vE,this.keyEncryptionAlgorithm=new AS,this.encryptedKey=new pm,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],wE.prototype,"version",void 0),Xm([qm({type:vE})],wE.prototype,"rid",void 0),Xm([qm({type:AS})],wE.prototype,"keyEncryptionAlgorithm",void 0),Xm([qm({type:pm})],wE.prototype,"encryptedKey",void 0);class SE{constructor(e={}){this.keyIdentifier=new pm,Object.assign(this,e)}}Xm([qm({type:pm})],SE.prototype,"keyIdentifier",void 0),Xm([qm({type:oy.GeneralizedTime,optional:!0})],SE.prototype,"date",void 0),Xm([qm({type:dE,optional:!0})],SE.prototype,"other",void 0);class EE{constructor(e={}){this.version=yS.v4,this.kekid=new SE,this.keyEncryptionAlgorithm=new AS,this.encryptedKey=new pm,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],EE.prototype,"version",void 0),Xm([qm({type:SE})],EE.prototype,"kekid",void 0),Xm([qm({type:AS})],EE.prototype,"keyEncryptionAlgorithm",void 0),Xm([qm({type:pm})],EE.prototype,"encryptedKey",void 0);class CE{constructor(e={}){this.version=yS.v0,this.keyEncryptionAlgorithm=new AS,this.encryptedKey=new pm,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],CE.prototype,"version",void 0),Xm([qm({type:wS,context:0,optional:!0})],CE.prototype,"keyDerivationAlgorithm",void 0),Xm([qm({type:AS})],CE.prototype,"keyEncryptionAlgorithm",void 0),Xm([qm({type:pm})],CE.prototype,"encryptedKey",void 0);class kE{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],kE.prototype,"oriType",void 0),Xm([qm({type:oy.Any})],kE.prototype,"oriValue",void 0);let xE=class{constructor(e={}){Object.assign(this,e)}};var BE;Xm([qm({type:wE,optional:!0})],xE.prototype,"ktri",void 0),Xm([qm({type:IE,context:1,implicit:!0,optional:!0})],xE.prototype,"kari",void 0),Xm([qm({type:EE,context:2,implicit:!0,optional:!0})],xE.prototype,"kekri",void 0),Xm([qm({type:CE,context:3,implicit:!0,optional:!0})],xE.prototype,"pwri",void 0),Xm([qm({type:kE,context:4,implicit:!0,optional:!0})],xE.prototype,"ori",void 0),xE=Xm([jm({type:ny.Choice})],xE);let _E=BE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,BE.prototype)}};var RE;_E=BE=Xm([jm({type:ny.Set,itemType:xE})],_E);class OE{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],OE.prototype,"otherRevInfoFormat",void 0),Xm([qm({type:oy.Any})],OE.prototype,"otherRevInfo",void 0);let UE=class{constructor(e={}){this.other=new OE,Object.assign(this,e)}};Xm([qm({type:OE,context:1,implicit:!0})],UE.prototype,"other",void 0),UE=Xm([jm({type:ny.Choice})],UE);let TE=RE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,RE.prototype)}};TE=RE=Xm([jm({type:ny.Set,itemType:UE})],TE);class NE{constructor(e={}){Object.assign(this,e)}}var DE;Xm([qm({type:oE,context:0,implicit:!0,optional:!0})],NE.prototype,"certs",void 0),Xm([qm({type:TE,context:1,implicit:!0,optional:!0})],NE.prototype,"crls",void 0);let ME=DE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,DE.prototype)}};ME=DE=Xm([jm({type:ny.Set,itemType:SS})],ME);class PE{constructor(e={}){this.version=yS.v0,this.recipientInfos=new _E,this.encryptedContentInfo=new uE,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],PE.prototype,"version",void 0),Xm([qm({type:NE,context:0,implicit:!0,optional:!0})],PE.prototype,"originatorInfo",void 0),Xm([qm({type:_E})],PE.prototype,"recipientInfos",void 0),Xm([qm({type:uE})],PE.prototype,"encryptedContentInfo",void 0),Xm([qm({type:ME,context:1,implicit:!0,optional:!0})],PE.prototype,"unprotectedAttrs",void 0);const LE="1.2.840.113549.1.7.2";var HE;let KE=HE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,HE.prototype)}};KE=HE=Xm([jm({type:ny.Set,itemType:mS})],KE);class VE{constructor(e={}){this.version=yS.v0,this.digestAlgorithms=new KE,this.encapContentInfo=new lE,this.signerInfos=new kS,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],VE.prototype,"version",void 0),Xm([qm({type:KE})],VE.prototype,"digestAlgorithms",void 0),Xm([qm({type:lE})],VE.prototype,"encapContentInfo",void 0),Xm([qm({type:oE,context:0,implicit:!0,optional:!0})],VE.prototype,"certificates",void 0),Xm([qm({type:TE,context:1,implicit:!0,optional:!0})],VE.prototype,"crls",void 0),Xm([qm({type:kS})],VE.prototype,"signerInfos",void 0);const QE="1.2.840.10045.2.1",FE="1.2.840.10045.4.1",GE="1.2.840.10045.4.3.1",$E="1.2.840.10045.4.3.2",jE="1.2.840.10045.4.3.3",qE="1.2.840.10045.4.3.4",zE="1.2.840.10045.3.1.7",WE="1.3.132.0.34",JE="1.3.132.0.35";function YE(e){return new tS({algorithm:e})}const ZE=YE(FE),XE=(YE(GE),YE($E)),eC=YE(jE),tC=YE(qE);let rC=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:oy.ObjectIdentifier})],rC.prototype,"fieldType",void 0),Xm([qm({type:oy.Any})],rC.prototype,"parameters",void 0),rC=Xm([jm({type:ny.Sequence})],rC);let sC=class{constructor(e={}){Object.assign(this,e)}};var iC;Xm([qm({type:oy.OctetString})],sC.prototype,"a",void 0),Xm([qm({type:oy.OctetString})],sC.prototype,"b",void 0),Xm([qm({type:oy.BitString,optional:!0})],sC.prototype,"seed",void 0),sC=Xm([jm({type:ny.Sequence})],sC),function(e){e[e.ecpVer1=1]="ecpVer1"}(iC||(iC={}));let nC=class{constructor(e={}){this.version=iC.ecpVer1,Object.assign(this,e)}};Xm([qm({type:oy.Integer})],nC.prototype,"version",void 0),Xm([qm({type:rC})],nC.prototype,"fieldID",void 0),Xm([qm({type:sC})],nC.prototype,"curve",void 0),Xm([qm({type:class extends pm{}})],nC.prototype,"base",void 0),Xm([qm({type:oy.Integer,converter:Am})],nC.prototype,"order",void 0),Xm([qm({type:oy.Integer,optional:!0})],nC.prototype,"cofactor",void 0),nC=Xm([jm({type:ny.Sequence})],nC);let oC=class{constructor(e={}){Object.assign(this,e)}};Xm([qm({type:oy.ObjectIdentifier})],oC.prototype,"namedCurve",void 0),Xm([qm({type:oy.Null})],oC.prototype,"implicitCurve",void 0),Xm([qm({type:nC})],oC.prototype,"specifiedCurve",void 0),oC=Xm([jm({type:ny.Choice})],oC);class aC{constructor(e={}){this.version=1,this.privateKey=new pm,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],aC.prototype,"version",void 0),Xm([qm({type:pm})],aC.prototype,"privateKey",void 0),Xm([qm({type:oC,context:0,optional:!0})],aC.prototype,"parameters",void 0),Xm([qm({type:oy.BitString,context:1,optional:!0})],aC.prototype,"publicKey",void 0);class cC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.Integer,converter:Am})],cC.prototype,"r",void 0),Xm([qm({type:oy.Integer,converter:Am})],cC.prototype,"s",void 0);const lC="1.2.840.113549.1.1",hC=`${lC}.1`,uC=`${lC}.7`,dC=`${lC}.9`,gC=`${lC}.10`,fC=`${lC}.2`,pC=`${lC}.4`,yC=`${lC}.5`,mC=`${lC}.14`,bC=`${lC}.11`,AC=`${lC}.12`,IC=`${lC}.13`,vC=`${lC}.15`,wC=`${lC}.16`,SC="1.3.14.3.2.26",EC="2.16.840.1.101.3.4.2.4",CC="2.16.840.1.101.3.4.2.1",kC="2.16.840.1.101.3.4.2.2",xC="2.16.840.1.101.3.4.2.3",BC=`${lC}.8`;function _C(e){return new tS({algorithm:e,parameters:null})}_C("1.2.840.113549.2.2"),_C("1.2.840.113549.2.5");const RC=_C(SC),OC=(_C(EC),_C(CC),_C(kC),_C(xC),_C("2.16.840.1.101.3.4.2.5"),_C("2.16.840.1.101.3.4.2.6"),new tS({algorithm:BC,parameters:Zm.serialize(RC)})),UC=new tS({algorithm:dC,parameters:Zm.serialize(Sm.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});_C(hC),_C(fC),_C(pC),_C(yC),_C(vC),_C(wC),_C(AC),_C(IC),_C(vC),_C(wC);class TC{constructor(e={}){this.hashAlgorithm=new tS(RC),this.maskGenAlgorithm=new tS({algorithm:BC,parameters:Zm.serialize(RC)}),this.pSourceAlgorithm=new tS(UC),Object.assign(this,e)}}Xm([qm({type:tS,context:0,defaultValue:RC})],TC.prototype,"hashAlgorithm",void 0),Xm([qm({type:tS,context:1,defaultValue:OC})],TC.prototype,"maskGenAlgorithm",void 0),Xm([qm({type:tS,context:2,defaultValue:UC})],TC.prototype,"pSourceAlgorithm",void 0),new tS({algorithm:uC,parameters:Zm.serialize(new TC)});class NC{constructor(e={}){this.hashAlgorithm=new tS(RC),this.maskGenAlgorithm=new tS({algorithm:BC,parameters:Zm.serialize(RC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Xm([qm({type:tS,context:0,defaultValue:RC})],NC.prototype,"hashAlgorithm",void 0),Xm([qm({type:tS,context:1,defaultValue:OC})],NC.prototype,"maskGenAlgorithm",void 0),Xm([qm({type:oy.Integer,context:2,defaultValue:20})],NC.prototype,"saltLength",void 0),Xm([qm({type:oy.Integer,context:3,defaultValue:1})],NC.prototype,"trailerField",void 0),new tS({algorithm:gC,parameters:Zm.serialize(new NC)});class DC{constructor(e={}){this.digestAlgorithm=new tS,this.digest=new pm,Object.assign(this,e)}}var MC;Xm([qm({type:tS})],DC.prototype,"digestAlgorithm",void 0),Xm([qm({type:pm})],DC.prototype,"digest",void 0);class PC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.Integer,converter:Am})],PC.prototype,"prime",void 0),Xm([qm({type:oy.Integer,converter:Am})],PC.prototype,"exponent",void 0),Xm([qm({type:oy.Integer,converter:Am})],PC.prototype,"coefficient",void 0);let LC=MC=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,MC.prototype)}};LC=MC=Xm([jm({type:ny.Sequence,itemType:PC})],LC);class HC{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.Integer})],HC.prototype,"version",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"modulus",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"publicExponent",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"privateExponent",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"prime1",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"prime2",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"exponent1",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"exponent2",void 0),Xm([qm({type:oy.Integer,converter:Am})],HC.prototype,"coefficient",void 0),Xm([qm({type:LC,optional:!0})],HC.prototype,"otherPrimeInfos",void 0);class KC{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var VC;Xm([qm({type:oy.Integer,converter:Am})],KC.prototype,"modulus",void 0),Xm([qm({type:oy.Integer,converter:Am})],KC.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(VC||(VC={}));const QC=VC;var FC=function(e,t){return FC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},FC(e,t)};function GC(e,t){function r(){this.constructor=e}FC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function $C(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function jC(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function qC(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(jC(arguments[t]));return e}function zC(e){return!!e.useClass}function WC(e){return!!e.useFactory}var JC=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,s=!1;return new Proxy({},this.createHandler(function(){return s||(t=e(r.wrap()),s=!0),t}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(r){t[r]=function(){for(var t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t[0]=e(),Reflect[r].apply(void 0,qC(t))}}),t},e}();function YC(e){return"string"==typeof e||"symbol"==typeof e}function ZC(e){return"object"==typeof e&&"token"in e&&"transform"in e}function XC(e){return!!e.useToken}function ek(e){return null!=e.useValue}var tk=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}();const rk=tk,sk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return GC(t,e),t}(rk),ik=function(){this.scopedResolutions=new Map};var nk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return GC(t,e),t}(rk),ok=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return GC(t,e),t}(rk);const ak=function(){this.preResolution=new nk,this.postResolution=new ok};var ck=new Map,lk=function(){function e(e){this.parent=e,this._registry=new sk,this.interceptors=new ak,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:QC.Transient}),this.ensureNotDisposed(),s=function(e){return zC(e)||ek(e)||XC(e)||WC(e)}(t)?t:{useClass:t},XC(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+qC(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&XC(a.provider)?a.provider:null}if((r.lifecycle===QC.Singleton||r.lifecycle==QC.ContainerScoped||r.lifecycle==QC.ResolutionScoped)&&(ek(s)||WC(s)))throw new Error('Cannot use lifecycle "'+QC[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),YC(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),YC(e)){if(YC(t))return this.register(e,{useToken:t},{lifecycle:QC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:QC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!YC(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:QC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new ik),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&YC(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var i=this.resolveRegistration(s,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof JC}(e))return i=this.construct(e,t),this.executePostResolutionInterceptor(e,i,"Single"),i;throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,s;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var n=$C(this.interceptors.preResolution.getAll(e)),o=n.next();!o.done;o=n.next()){var a=o.value;"Once"!=a.options.frequency&&i.push(a),a.callback(e,t)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var s,i;if(this.interceptors.postResolution.has(e)){var n=[];try{for(var o=$C(this.interceptors.postResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===QC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===QC.Singleton,i=e.options.lifecycle===QC.ContainerScoped,n=s||i;return r=ek(e.provider)?e.provider.useValue:XC(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):zC(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):WC(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===QC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new ik),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&YC(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var n=i.map(function(e){return s.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,n,"All"),n}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,"All"),o},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=$C(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=jC(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!ek(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var s=new e(this);try{for(var i=$C(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=jC(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===QC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===QC.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,s&&(i=2&n[0]?s.return:n[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,n[1])).done)return i;switch(s=0,i&&(n=[2&n[0],i.value]),n[0]){case 0:case 1:i=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){o.label=n[1];break}if(6===n[0]&&o.label<i[1]){o.label=i[1],i=n;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(n);break}i[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(e){n=[6,e],s=0}finally{r=i=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}}(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var r=t.dispose();r&&e.push(r)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof JC)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=ck.get(e);if(!s||0===s.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(r.resolveParams(t,e));return new(e.bind.apply(e,qC([void 0],i)))}();return"function"!=typeof(s=i).dispose||s.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(s,i){var n,o,a,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?ZC(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,qC([r.resolveAll(s.token,new ik,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,qC([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new ik,s.isOptional):r.resolve(s.token,e,s.isOptional):ZC(s)?(a=r.resolve(s.transform,e)).transform.apply(a,qC([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=jC(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),qC([e],t.message.split("\n").map(function(e){return r+e})).join("\n")}("Cannot inject the dependency "+(i=t,(null===(s=void 0===n?null:n)?"at position #"+i:'"'+s.split(",")[i].trim()+'" at position #'+i)+' of "')+e.name+'" constructor. Reason:',r)}(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),hk=new lk;const uk=function(e){return function(t){ck.set(t,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach(function(e){t[+e]=r[e]}),t}(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){hk.register(e,t)}):hk.register(e.token,t))}};if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");var dk;class gk{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Xm([qm({type:oy.ObjectIdentifier})],gk.prototype,"attrId",void 0),Xm([qm({type:oy.Any,repeated:"set"})],gk.prototype,"attrValues",void 0);let fk=dk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,dk.prototype)}};var pk;fk=dk=Xm([jm({type:ny.Sequence,itemType:gk})],fk);let yk=pk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,pk.prototype)}};yk=pk=Xm([jm({type:ny.Sequence,itemType:aE})],yk);class mk{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],mk.prototype,"certId",void 0),Xm([qm({type:oy.Any,context:0})],mk.prototype,"certValue",void 0);class bk{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],bk.prototype,"crlId",void 0),Xm([qm({type:oy.Any,context:0})],bk.prototype,"crltValue",void 0);class Ak extends pm{}class Ik{constructor(e={}){this.encryptionAlgorithm=new tS,this.encryptedData=new Ak,Object.assign(this,e)}}var vk,wk;Xm([qm({type:tS})],Ik.prototype,"encryptionAlgorithm",void 0),Xm([qm({type:Ak})],Ik.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(wk||(wk={}));class Sk extends pm{}let Ek=vk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,vk.prototype)}};Ek=vk=Xm([jm({type:ny.Sequence,itemType:Gw})],Ek);class Ck{constructor(e={}){this.version=wk.v1,this.privateKeyAlgorithm=new tS,this.privateKey=new Sk,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],Ck.prototype,"version",void 0),Xm([qm({type:tS})],Ck.prototype,"privateKeyAlgorithm",void 0),Xm([qm({type:Sk})],Ck.prototype,"privateKey",void 0),Xm([qm({type:Ek,implicit:!0,context:0,optional:!0})],Ck.prototype,"attributes",void 0);let kk=class extends Ck{};kk=Xm([jm({type:ny.Sequence})],kk);let xk=class extends Ik{};xk=Xm([jm({type:ny.Sequence})],xk);class Bk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Bk.prototype,"secretTypeId",void 0),Xm([qm({type:oy.Any,context:0})],Bk.prototype,"secretValue",void 0);class _k{constructor(e={}){this.mac=new DC,this.macSalt=new pm,this.iterations=1,Object.assign(this,e)}}Xm([qm({type:DC})],_k.prototype,"mac",void 0),Xm([qm({type:pm})],_k.prototype,"macSalt",void 0),Xm([qm({type:oy.Integer,defaultValue:1})],_k.prototype,"iterations",void 0);class Rk{constructor(e={}){this.version=3,this.authSafe=new aE,this.macData=new _k,Object.assign(this,e)}}var Ok;Xm([qm({type:oy.Integer})],Rk.prototype,"version",void 0),Xm([qm({type:aE})],Rk.prototype,"authSafe",void 0),Xm([qm({type:_k,optional:!0})],Rk.prototype,"macData",void 0);class Uk{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:oy.ObjectIdentifier})],Uk.prototype,"bagId",void 0),Xm([qm({type:oy.Any,context:0})],Uk.prototype,"bagValue",void 0),Xm([qm({type:gk,repeated:"set",optional:!0})],Uk.prototype,"bagAttributes",void 0);let Tk=Ok=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Ok.prototype)}};var Nk,Dk,Mk;Tk=Ok=Xm([jm({type:ny.Sequence,itemType:Uk})],Tk);const Pk="1.2.840.113549.1.9",Lk=`${Pk}.7`,Hk=`${Pk}.14`;let Kk=class extends mv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Xm([qm({type:oy.IA5String})],Kk.prototype,"ia5String",void 0),Kk=Xm([jm({type:ny.Choice})],Kk);let Vk=class extends aE{};Vk=Xm([jm({type:ny.Sequence})],Vk);let Qk=class extends Rk{};Qk=Xm([jm({type:ny.Sequence})],Qk);let Fk=class extends Ik{};Fk=Xm([jm({type:ny.Sequence})],Fk);let Gk=class{constructor(e=""){this.value=e}toString(){return this.value}};Xm([qm({type:oy.IA5String})],Gk.prototype,"value",void 0),Gk=Xm([jm({type:ny.Choice})],Gk);let $k=class extends Kk{};$k=Xm([jm({type:ny.Choice})],$k);let jk=class extends mv{};jk=Xm([jm({type:ny.Choice})],jk);let qk=class{constructor(e=new Date){this.value=e}};Xm([qm({type:oy.GeneralizedTime})],qk.prototype,"value",void 0),qk=Xm([jm({type:ny.Choice})],qk);let zk=class extends mv{};zk=Xm([jm({type:ny.Choice})],zk);let Wk=class{constructor(e="M"){this.value=e}toString(){return this.value}};Xm([qm({type:oy.PrintableString})],Wk.prototype,"value",void 0),Wk=Xm([jm({type:ny.Choice})],Wk);let Jk=class{constructor(e=""){this.value=e}toString(){return this.value}};Xm([qm({type:oy.PrintableString})],Jk.prototype,"value",void 0),Jk=Xm([jm({type:ny.Choice})],Jk);let Yk=class extends Jk{};Yk=Xm([jm({type:ny.Choice})],Yk);let Zk=class extends mv{};Zk=Xm([jm({type:ny.Choice})],Zk);let Xk=class{constructor(e=""){this.value=e}toString(){return this.value}};Xm([qm({type:oy.ObjectIdentifier})],Xk.prototype,"value",void 0),Xk=Xm([jm({type:ny.Choice})],Xk);let ex=class extends sS{};ex=Xm([jm({type:ny.Choice})],ex);let tx=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Xm([qm({type:oy.Integer})],tx.prototype,"value",void 0),tx=Xm([jm({type:ny.Choice})],tx);let rx=class extends CS{};rx=Xm([jm({type:ny.Sequence})],rx);let sx=class extends mv{};sx=Xm([jm({type:ny.Choice})],sx);let ix=Nk=class extends aS{constructor(e){super(e),Object.setPrototypeOf(this,Nk.prototype)}};ix=Nk=Xm([jm({type:ny.Sequence})],ix);let nx=Dk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Dk.prototype)}};nx=Dk=Xm([jm({type:ny.Set,itemType:SS})],nx);let ox=class{constructor(e=""){this.value=e}toString(){return this.value}};Xm([qm({type:oy.BmpString})],ox.prototype,"value",void 0),ox=Xm([jm({type:ny.Choice})],ox);let ax=class extends tS{};ax=Xm([jm({type:ny.Sequence})],ax);let cx=Mk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Mk.prototype)}};var lx;cx=Mk=Xm([jm({type:ny.Sequence,itemType:ax})],cx);let hx=lx=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,lx.prototype)}};hx=lx=Xm([jm({type:ny.Sequence,itemType:Gw})],hx);class ux{constructor(e={}){this.version=0,this.subject=new wv,this.subjectPKInfo=new rS,this.attributes=new hx,Object.assign(this,e)}}Xm([qm({type:oy.Integer})],ux.prototype,"version",void 0),Xm([qm({type:wv})],ux.prototype,"subject",void 0),Xm([qm({type:rS})],ux.prototype,"subjectPKInfo",void 0),Xm([qm({type:hx,implicit:!0,context:0})],ux.prototype,"attributes",void 0);class dx{constructor(e={}){this.certificationRequestInfo=new ux,this.signatureAlgorithm=new tS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Xm([qm({type:ux})],dx.prototype,"certificationRequestInfo",void 0),Xm([qm({type:tS})],dx.prototype,"signatureAlgorithm",void 0),Xm([qm({type:oy.BitString})],dx.prototype,"signature",void 0);const gx="crypto.algorithm",fx="crypto.algorithmProvider";var px;hk.registerSingleton(fx,class{getAlgorithms(){return hk.resolveAll(gx)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new tS({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const yx="1.3.36.3.3.2.8.1.1",mx=`${yx}.1`,bx=`${yx}.2`,Ax=`${yx}.3`,Ix=`${yx}.4`,vx=`${yx}.5`,wx=`${yx}.6`,Sx=`${yx}.7`,Ex=`${yx}.8`,Cx=`${yx}.9`,kx=`${yx}.10`,xx=`${yx}.11`,Bx=`${yx}.12`,_x=`${yx}.13`,Rx=`${yx}.14`,Ox="brainpoolP160r1",Ux="brainpoolP160t1",Tx="brainpoolP192r1",Nx="brainpoolP192t1",Dx="brainpoolP224r1",Mx="brainpoolP224t1",Px="brainpoolP256r1",Lx="brainpoolP256t1",Hx="brainpoolP320r1",Kx="brainpoolP320t1",Vx="brainpoolP384r1",Qx="brainpoolP384t1",Fx="brainpoolP512r1",Gx="brainpoolP512t1",$x="ECDSA";let jx=px=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===$x.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return ZE;case"sha-256":return XE;case"sha-384":return eC;case"sha-512":return tC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=zE;break;case"K-256":t=px.SECP256K1;break;case"P-384":t=WE;break;case"P-521":t=JE;break;case Ox:t=mx;break;case Ux:t=bx;break;case Tx:t=Ax;break;case Nx:t=Ix;break;case Dx:t=vx;break;case Mx:t=wx;break;case Px:t=Sx;break;case Lx:t=Ex;break;case Hx:t=Cx;break;case Kx:t=kx;break;case Vx:t=xx;break;case Qx:t=Bx;break;case Fx:t=_x;break;case Gx:t=Rx}if(t)return new tS({algorithm:QE,parameters:Zm.serialize(new oC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case FE:return{name:$x,hash:{name:"SHA-1"}};case $E:return{name:$x,hash:{name:"SHA-256"}};case jE:return{name:$x,hash:{name:"SHA-384"}};case qE:return{name:$x,hash:{name:"SHA-512"}};case QE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Zm.parse(e.parameters,oC).namedCurve){case zE:return{name:$x,namedCurve:"P-256"};case px.SECP256K1:return{name:$x,namedCurve:"K-256"};case WE:return{name:$x,namedCurve:"P-384"};case JE:return{name:$x,namedCurve:"P-521"};case mx:return{name:$x,namedCurve:Ox};case bx:return{name:$x,namedCurve:Ux};case Ax:return{name:$x,namedCurve:Tx};case Ix:return{name:$x,namedCurve:Nx};case vx:return{name:$x,namedCurve:Dx};case wx:return{name:$x,namedCurve:Mx};case Sx:return{name:$x,namedCurve:Px};case Ex:return{name:$x,namedCurve:Lx};case Cx:return{name:$x,namedCurve:Hx};case kx:return{name:$x,namedCurve:Kx};case xx:return{name:$x,namedCurve:Vx};case Bx:return{name:$x,namedCurve:Qx};case _x:return{name:$x,namedCurve:Fx};case Rx:return{name:$x,namedCurve:Gx}}}return null}};jx.SECP256K1="1.3.132.0.10",jx=px=Xm([uk()],jx),hk.registerSingleton(gx,jx);const qx=Symbol("name"),zx=Symbol("value");class Wx{constructor(e,t={},r=""){this[qx]=e,this[zx]=r;for(const e in t)this[e]=t[e]}}Wx.NAME=qx,Wx.VALUE=zx;class Jx{static toString(e){return this.items[e]||e}}Jx.items={[SC]:"sha1",[EC]:"sha224",[CC]:"sha256",[kC]:"sha384",[xC]:"sha512",[hC]:"rsaEncryption",[yC]:"sha1WithRSAEncryption",[mC]:"sha224WithRSAEncryption",[bC]:"sha256WithRSAEncryption",[AC]:"sha384WithRSAEncryption",[IC]:"sha512WithRSAEncryption",[QE]:"ecPublicKey",[FE]:"ecdsaWithSHA1",[GE]:"ecdsaWithSHA224",[$E]:"ecdsaWithSHA256",[jE]:"ecdsaWithSHA384",[qE]:"ecdsaWithSHA512",[Iw]:"TLS WWW server authentication",[vw]:"TLS WWW client authentication",[ww]:"Code Signing",[Sw]:"E-mail Protection",[Ew]:"Time Stamping",[Cw]:"OCSP Signing",[LE]:"Signed Data"};class Yx{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let s=this.pad(t++),i="";const n=e[Wx.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[Wx.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],o=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${o}${n}`);else if(n instanceof Date)r.push(`${s}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[Wx.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof Wx)n[Wx.NAME]=i,r.push(...this.serializeObj(n,t));else if(Tf.isBufferSource(n))i?(r.push(`${s}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[Wx.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=Tf.toUint8Array(e),i=[];for(let e=0;e<s.length;){const t=[];for(let r=0;r<16&&e<s.length;r++){8===r&&t.push("");const i=s[e++].toString(16).padStart(2,"0");t.push(i)}i.push(`${r}${t.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Yx.oidSerializer=Jx,Yx.algorithmSerializer=class{static toTextObject(e){const t=new Wx("Algorithm Identifier",{},Jx.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case QE:{const r=(new jx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Zx{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Zm.serialize(t),this.onInit(t)}else{const t=Zm.parse(e[0],e[1]);this.rawData=Tf.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Zx&&Qf(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Zm.toString(this.rawData);case"text":return Yx.serialize(this.toTextObject());case"hex":return Kf.ToHex(this.rawData);case"base64":return Kf.ToBase64(this.rawData);case"base64url":return Kf.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Wx(this.getTextName(),{},e)}}Zx.NAME="ASN";class Xx extends Zx{constructor(...e){let t;t=Tf.isBufferSource(e[0])?Tf.toArrayBuffer(e[0]):Zm.serialize(new oS({extnID:e[0],critical:e[1],extnValue:new pm(Tf.toArrayBuffer(e[2]))})),super(t,oS)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Wx.NAME]===Xx.NAME&&(e[Wx.NAME]=Jx.toString(this.type)),e}}var eB;class tB{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[eB]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(tB.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(tB.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=tB.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(tB.DEFAULT,e);return this}}eB=Symbol.toStringTag,tB.DEFAULT="default";const rB=new tB,sB=/^[0-2](?:\.[1-9][0-9]*)+$/;class iB{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(sB).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const nB=new iB;function oB(e,t){return`\\${Kf.ToHex(Kf.FromUtf8String(t)).toUpperCase()}`}nB.register("CN","2.5.4.3"),nB.register("L","2.5.4.7"),nB.register("ST","2.5.4.8"),nB.register("O","2.5.4.10"),nB.register("OU","2.5.4.11"),nB.register("C","2.5.4.6"),nB.register("DC","0.9.2342.19200300.100.1.25"),nB.register("E","1.2.840.113549.1.9.1"),nB.register("G","2.5.4.42"),nB.register("I","2.5.4.43"),nB.register("SN","2.5.4.4"),nB.register("T","2.5.4.12");class aB{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new iB,this.asn=new wv;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const r=t[e];this.extraNames.register(e,r)}"string"==typeof e?this.asn=this.fromString(e):e instanceof wv?this.asn=e:Tf.isBufferSource(e)?this.asn=Zm.parse(e,wv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||nB.findId(e),r=[];for(const e of this.asn)for(const s of e)s.type===t&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||nB.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Kf.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,oB)}`).join("+")).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const s={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=s[r])&&void 0!==e||(s[r]=[]),s[r].push(t.value.anyValue?`#${Kf.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new wv,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,i=",";for(;s=r.exec(`${e},`);){let[,e,r]=s;const n=r[r.length-1];","!==n&&"+"!==n||(r=r.slice(0,r.length-1),s[3]=n);const o=s[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===i?t[t.length-1].push(a):t.push(new Iv([a])),i=o}return t}fromJSON(e){const t=new wv;for(const r of e){const e=new Iv;for(const t in r){const s=this.getTypeOid(t),i=r[t];for(const t of i){const r=this.createAttribute(s,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new Av({type:e});if("object"==typeof t)for(const e in t)switch(e){case"ia5String":r.value.ia5String=t[e];break;case"utf8String":r.value.utf8String=t[e];break;case"universalString":r.value.universalString=t[e];break;case"bmpString":r.value.bmpString=t[e];break;case"printableString":r.value.printableString=t[e]}else if("#"===t[0])r.value.anyValue=Kf.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:aB.isPrintableString(s)?r.value.printableString=s:r.value.utf8String=s}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Zm.serialize(this.asn)}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||rB.get()):r=e[0]||rB.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const cB="Cannot initialize GeneralName from ASN.1 data.",lB=`${cB} Unsupported string format in use.`,hB=`${cB} Value doesn't match to GUID regular expression.`,uB=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,dB="1.3.6.1.4.1.311.25.1",gB="1.3.6.1.4.1.311.20.2.3",fB="dns",pB="dn",yB="email",mB="ip",bB="url",AB="guid",IB="upn",vB="id";class wB extends Zx{constructor(...e){let t;if(2===e.length)switch(e[0]){case pB:{const r=new aB(e[1]).toArrayBuffer(),s=Zm.parse(r,wv);t=new kv({directoryName:s});break}case fB:t=new kv({dNSName:e[1]});break;case yB:t=new kv({rfc822Name:e[1]});break;case AB:{const r=new RegExp(uB,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=r.slice(1).map((e,t)=>t<3?Kf.ToHex(new Uint8Array(Kf.FromHex(e)).reverse()):e).join("");t=new kv({otherName:new Ev({typeId:dB,value:Zm.serialize(new pm(Kf.FromHex(s)))})});break}case mB:t=new kv({iPAddress:e[1]});break;case vB:t=new kv({registeredID:e[1]});break;case IB:t=new kv({otherName:new Ev({typeId:gB,value:Zm.serialize(km.toASN(e[1]))})});break;case bB:t=new kv({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=Tf.isBufferSource(e[0])?Zm.parse(e[0],kv):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=fB,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=yB,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=mB,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=bB,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=vB,this.value=e.registeredID;else if(null!=e.directoryName)this.type=pB,this.value=new aB(e.directoryName).toString();else{if(null==e.otherName)throw new Error(lB);if(e.otherName.typeId===dB){this.type=AB;const t=Zm.parse(e.otherName.value,pm),r=new RegExp(uB,"i").exec(Kf.ToHex(t));if(!r)throw new Error(hB);this.value=r.slice(1).map((e,t)=>t<3?Kf.ToHex(new Uint8Array(Kf.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==gB)throw new Error(lB);this.type=IB,this.value=Zm.parse(e.otherName.value,mv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case pB:case fB:case AB:case mB:case vB:case IB:case bB:e=this.type.toUpperCase();break;case yB:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===vB&&(t=Jx.toString(t)),new Wx(e,void 0,t)}}class SB extends Zx{constructor(e){let t;if(e instanceof $v)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof kv)r.push(t);else{const e=Zm.parse(new wB(t.type,t.value).rawData,kv);r.push(e)}t=new $v(r)}else{if(!Tf.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Zm.parse(e,$v)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new wB(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let s=e[r[Wx.NAME]];Array.isArray(s)||(s=[],e[r[Wx.NAME]]=s),s.push(r)}return e}}SB.NAME="GeneralNames";const EB="-{5}",CB="\\n",kB="\\n",xB=`${EB}BEGIN ([^${CB}]+(?=${EB}))${EB}${kB}(?:((?:[^:${CB}]+: (?:[^${CB}]+${kB}(?: +[^${CB}]+${kB})*))+))?${kB}?((?:[a-zA-Z0-9=+/]+${kB})+)${EB}END \\1${EB}`;class BB{static isPem(e){return"string"==typeof e&&new RegExp(xB,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(xB,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${CB}]+`,"g"),""),t={type:s[1],headers:[],rawData:Kf.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(kB,"g"));let r=null;for(const s of e){const[e,i]=s.split(/:(.*)/);if(void 0===i){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:i.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach(e=>{if(!Tf.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:Tf.toArrayBuffer(e)}))}):e.forEach(e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))}),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:Tf.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)s.push(`${t.key}: ${t.value}`);s.push("")}const i=Kf.ToBase64(e.rawData);let n,o=0;const a=Array();for(;o<i.length&&(i.length-o<64?n=i.substring(o):(n=i.substring(o,o+64),o+=64),0!==n.length)&&(a.push(n),!(n.length<64)););return s.push(...a),s.push(`-----END ${r}-----`),s.join("\n")}}BB.CertificateTag="CERTIFICATE",BB.CrlTag="CRL",BB.CertificateRequestTag="CERTIFICATE REQUEST",BB.PublicKeyTag="PUBLIC KEY",BB.PrivateKeyTag="PRIVATE KEY";class _B extends Zx{static isAsnEncoded(e){return Tf.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(BB.isPem(e))return BB.decode(e)[0];if(Kf.isHex(e))return Kf.FromHex(e);if(Kf.isBase64(e))return Kf.FromBase64(e);if(Kf.isBase64Url(e))return Kf.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Kf.ToBinary(e);return BB.isPem(t)?BB.decode(t)[0]:Kf.isHex(t)?Kf.FromHex(t):Kf.isBase64(t)?Kf.FromBase64(t):Kf.isBase64Url(t)?Kf.FromBase64Url(t):Tf.toArrayBuffer(e)}}constructor(...e){_B.isAsnEncoded(e[0])?super(_B.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?BB.encode(this.rawData,this.tag):super.toString(e)}}class RB extends _B{static async create(e,t=rB.get()){if(e instanceof RB)return e;if(tB.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new RB(r)}if(e.publicKey)return e.publicKey;if(Tf.isBufferSource(e))return new RB(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){_B.isAsnEncoded(e)?super(e,rS):super(e),this.tag=BB.PublicKeyTag}async export(...e){let t,r=["verify"],s={hash:"SHA-256",...this.algorithm};e.length>1?(s=e[0]||s,r=e[1]||r,t=e[2]||rB.get()):t=e[0]||rB.get();let i=this.rawData;const n=Zm.parse(this.rawData,rS);return n.algorithm.algorithm===gC&&(i=function(e){return e.algorithm=new tS({algorithm:hC,parameters:null}),Zm.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=hk.resolve(fx),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case hC:{const t=Zm.parse(e.subjectPublicKey,KC),s=Tf.toUint8Array(t.modulus);r.publicExponent=Tf.toUint8Array(t.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||rB.get()):r=e[0]||rB.get(),await r.subtle.digest(s,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=rB.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=rB.get();const s=Zm.parse(this.rawData,rS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Zm.parse(this.rawData,rS);return e.Algorithm=Yx.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===QE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class OB extends Xx{static async create(e,t=!1,r=rB.get()){if("name"in e&&"serialNumber"in e)return new OB(e,t);const s=await RB.create(e,r),i=await s.getKeyIdentifier(r);return new OB(Kf.ToHex(i),t)}constructor(...e){if(Tf.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Vv({keyIdentifier:new Kv(Kf.FromHex(e[0]))});super(Hv,e[1],Zm.serialize(t))}else{const t=e[0],r=t.name instanceof SB?Zm.parse(t.name.rawData,$v):t.name,s=new Vv({authorityCertIssuer:r,authorityCertSerialNumber:Kf.FromHex(t.serialNumber)});super(Hv,e[1],Zm.serialize(s))}}onInit(e){super.onInit(e);const t=Zm.parse(e.extnValue,Vv);t.keyIdentifier&&(this.keyId=Kf.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Kf.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Zm.parse(this.value,Vv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new SB(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}OB.NAME="Authority Key Identifier";class UB extends Xx{constructor(...e){if(Tf.isBufferSource(e[0])){super(e[0]);const t=Zm.parse(this.value,Fv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Fv({cA:e[0],pathLenConstraint:e[1]});super(Qv,e[2],Zm.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var TB,NB;UB.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(TB||(TB={}));class DB extends Xx{constructor(...e){if(Tf.isBufferSource(e[0])){super(e[0]);const t=Zm.parse(this.value,Aw);this.usages=t.map(e=>e)}else{const t=new Aw(e[0]);super(bw,e[1],Zm.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Jx.toString(e)).join(", "),e}}DB.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(NB||(NB={}));class MB extends Xx{constructor(...e){if(Tf.isBufferSource(e[0])){super(e[0]);const t=Zm.parse(this.value,Tw);this.usages=t.toNumber()}else{const t=new Tw(e[0]);super(Rw,e[1],Zm.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Zm.parse(this.value,Tw);return e[""]=t.toJSON().join(", "),e}}MB.NAME="Key Usages";class PB extends Xx{static async create(e,t=!1,r=rB.get()){const s=await RB.create(e,r),i=await s.getKeyIdentifier(r);return new PB(Kf.ToHex(i),t)}constructor(...e){if(Tf.isBufferSource(e[0])){super(e[0]);const t=Zm.parse(this.value,zw);this.keyId=Kf.ToHex(t)}else{const t="string"==typeof e[0]?Kf.FromHex(e[0]):e[0],r=new zw(t);super(qw,e[1],Zm.serialize(r)),this.keyId=Kf.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Zm.parse(this.value,zw);return e[""]=t,e}}PB.NAME="Subject Key Identifier";class LB extends Xx{constructor(...e){Tf.isBufferSource(e[0])?super(e[0]):super(Qw,e[1],new SB(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Zm.parse(e.extnValue,Fw);this.names=new SB(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}LB.NAME="Subject Alternative Name";class HB{static register(e,t){this.items.set(e,t)}static create(e){const t=new Xx(e),r=this.items.get(t.type);return r?new r(e):t}}HB.items=new Map;class KB extends Xx{constructor(...e){var t;if(Tf.isBufferSource(e[0])){super(e[0]);const t=Zm.parse(this.value,rw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new rw(r.map(e=>new tw({policyIdentifier:e})));super(Wv,s,Zm.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new Wx("",{},Jx.toString(e))),e}}KB.NAME="Certificate Policies",HB.register(Wv,KB);class VB extends Xx{constructor(...e){var t;if(Tf.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new hw({distributionPoint:new lw({fullName:[new kv({uniformResourceIdentifier:e})]})})),r=new uw(t);super(ow,e[1],Zm.serialize(r))}else{const t=new uw(e[0]);super(ow,e[1],Zm.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Zm.parse(e.extnValue,uw);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map(e=>new wB(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}VB.NAME="CRL Distribution Points";class QB extends Xx{constructor(...e){var t,r,s,i;if(Tf.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Lv){const t=new Lv(e[0]);super(Mv,e[1],Zm.serialize(t))}else{const t=e[0],r=new Lv;GB(r,t,Rv,"ocsp"),GB(r,t,Ov,"caIssuers"),GB(r,t,Uv,"timeStamping"),GB(r,t,Tv,"caRepository"),super(Mv,e[1],Zm.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(s=this.timeStamping)&&void 0!==s||(this.timeStamping=[]),null!==(i=this.caRepository)&&void 0!==i||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Zm.parse(e.extnValue,Lv).forEach(e=>{switch(e.accessMethod){case Rv:this.ocsp.push(new wB(e.accessLocation));break;case Ov:this.caIssuers.push(new wB(e.accessLocation));break;case Uv:this.timeStamping.push(new wB(e.accessLocation));break;case Tv:this.caRepository.push(new wB(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&FB(e,"OCSP",this.ocsp),this.caIssuers.length&&FB(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&FB(e,"Time Stamping",this.timeStamping),this.caRepository.length&&FB(e,"CA Repository",this.caRepository),e}}function FB(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new Wx("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[Wx.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function GB(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new wB("url",t)),e.push(new Pv({accessMethod:r,accessLocation:Zm.parse(t.rawData,kv)}))})}QB.NAME="Authority Info Access";class $B extends Zx{constructor(...e){let t;if(Tf.isBufferSource(e[0]))t=Tf.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>Tf.toArrayBuffer(e)):[];t=Zm.serialize(new Gw({type:r,values:s}))}super(t,Gw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new Wx("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[Wx.NAME]===$B.NAME&&(e[Wx.NAME]=Jx.toString(this.type)),e}}$B.NAME="Attribute";class jB extends $B{constructor(...e){var t;if(Tf.isBufferSource(e[0]))super(e[0]);else{const t=new sx({printableString:e[0]});super(Lk,[Zm.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Zm.parse(this.values[0],sx);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[Wx.VALUE]=this.password,e}}jB.NAME="Challenge Password";class qB extends $B{constructor(...e){var t;if(Tf.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new aS;for(const e of t)r.push(Zm.parse(e.rawData,oS));super(Hk,[Zm.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Zm.parse(this.values[0],aS);this.items=e.map(e=>HB.create(Zm.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[Wx.NAME]]=r;return e}}qB.NAME="Extensions";class zB{static register(e,t){this.items.set(e,t)}static create(e){const t=new $B(e),r=this.items.get(t.type);return r?new r(e):t}}zB.items=new Map;const WB="crypto.signatureFormatter";var JB;let YB=JB=class{static createPssParams(e,t){const r=JB.getHashAlgorithm(e);return r?new NC({hashAlgorithm:r,maskGenAlgorithm:new tS({algorithm:BC,parameters:Zm.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=hk.resolve(fx);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new tS({algorithm:hC,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new tS({algorithm:yC,parameters:null});case"sha-256":return new tS({algorithm:bC,parameters:null});case"sha-384":return new tS({algorithm:AC,parameters:null});case"sha-512":return new tS({algorithm:IC,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=JB.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new tS({algorithm:gC,parameters:Zm.serialize(t)})}return new tS({algorithm:gC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case hC:return{name:"RSASSA-PKCS1-v1_5"};case yC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case bC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case AC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case IC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case gC:if(e.parameters){const t=Zm.parse(e.parameters,NC);return{name:"RSA-PSS",hash:hk.resolve(fx).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};YB=JB=Xm([uk()],YB),hk.registerSingleton(gx,YB);let ZB=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new tS({algorithm:SC});case"sha-256":return new tS({algorithm:CC});case"sha-384":return new tS({algorithm:kC});case"sha-512":return new tS({algorithm:xC})}return null}toWebAlgorithm(e){switch(e.algorithm){case SC:return{name:"SHA-1"};case CC:return{name:"SHA-256"};case kC:return{name:"SHA-384"};case xC:return{name:"SHA-512"}}return null}};ZB=Xm([uk()],ZB),hk.registerSingleton(gx,ZB);class XB{addPadding(e,t){const r=Tf.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=Tf.toUint8Array(e);for(let e=0;e<r.length;e++)if(r[e]){r=r.slice(e);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,s=XB.namedCurveSize.get(r)||XB.defaultNamedCurveSize,i=new cC,n=Tf.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Zm.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Zm.parse(t,cC),s=e.namedCurve,i=XB.namedCurveSize.get(s)||XB.defaultNamedCurveSize;return Vf(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}XB.namedCurveSize=new Map,XB.defaultNamedCurveSize=32;const e_="1.3.101.110",t_="1.3.101.111",r_="1.3.101.112",s_="1.3.101.113";let i_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=r_;break;case"x25519":t=e_;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=r_;break;case"ed448":t=s_}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=e_;break;case"x448":t=t_}}return t?new tS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case r_:return{name:"Ed25519"};case s_:return{name:"EdDSA",namedCurve:"Ed448"};case e_:return{name:"X25519"};case t_:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};i_=Xm([uk()],i_),hk.registerSingleton(gx,i_);(class extends _B{constructor(e){_B.isAsnEncoded(e)?super(e,dx):super(e),this.tag=BB.CertificateRequestTag}onInit(e){this.tbs=Zm.serialize(e.certificationRequestInfo),this.publicKey=new RB(e.certificationRequestInfo.subjectPKInfo);const t=hk.resolve(fx);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>zB.create(Zm.serialize(e)));const r=this.getAttribute(Hk);this.extensions=[],r instanceof qB&&(this.extensions=r.items),this.subjectName=new aB(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=rB.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=hk.resolveAll(WB).reverse();let i=null;for(const e of s)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,i,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=Zm.parse(this.rawData,dx),r=t.certificationRequestInfo,s=new Wx("",{Version:`${cS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new Wx("");for(const t of this.attributes){const r=t.toTextObject();e[r[Wx.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new Wx("",{Algorithm:Yx.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var n_;(class extends _B{constructor(e){_B.isAsnEncoded(e)?super(e,hS):super(e),this.tag=BB.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Zm.serialize(t),this.serialNumber=Kf.ToHex(t.serialNumber),this.subjectName=new aB(t.subject),this.subject=new aB(t.subject).toString(),this.issuerName=new aB(t.issuer),this.issuer=this.issuerName.toString();const r=hk.resolve(fx);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;const s=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!s)throw new Error("Cannot get 'notBefore' value");this.notBefore=s;const i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>HB.create(Zm.serialize(e)))),this.publicKey=new RB(t.subjectPublicKeyInfo)}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>"string"==typeof e?t.type===e:t instanceof e)}async verify(e={},t=rB.get()){let r,s;const i=e.publicKey;try{if(i)if("publicKey"in i)r={...i.publicKey.algorithm,...this.signatureAlgorithm},s=await i.publicKey.export(r,["verify"],t);else if(i instanceof RB)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(Tf.isBufferSource(i)){const e=new RB(i);r={...e.algorithm,...this.signatureAlgorithm},s=await e.export(r,["verify"],t)}else r={...i.algorithm,...this.signatureAlgorithm},s=i;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],t)}catch(e){return!1}const n=hk.resolveAll(WB).reverse();let o=null;for(const e of n)if(o=e.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,s,o,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=rB.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=rB.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Zm.parse(this.rawData,hS),r=t.tbsCertificate,s=new Wx("",{Version:`${cS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Yx.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Wx("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(s["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(s["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new Wx("");for(const t of this.extensions){const r=t.toTextObject();e[r[Wx.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new Wx("",{Algorithm:Yx.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}).NAME="Certificate",function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(n_||(n_={})),HB.register(Qv,UB),HB.register(bw,DB),HB.register(Rw,MB),HB.register(qw,PB),HB.register(Hv,OB),HB.register(Qw,LB),HB.register(ow,VB),HB.register(Mv,QB),zB.register(Lk,jB),zB.register(Hk,qB),hk.registerSingleton(WB,class{toAsnSignature(e,t){return Tf.toArrayBuffer(t)}toWebSignature(e,t){return Tf.toArrayBuffer(t)}}),hk.registerSingleton(WB,XB),XB.namedCurveSize.set("P-256",32),XB.namedCurveSize.set("K-256",32),XB.namedCurveSize.set("P-384",48),XB.namedCurveSize.set("P-521",66),Gs.new(void 0,"networking");const o_=new class extends KA{constructor(){super(...arguments),this.subtle=new dv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=$A.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return qA().randomFillSync(t),e}};var a_,c_,l_;function h_(e){return W(e)}rB.set(o_),(l_=a_||(a_={}))[l_.NoCertificate=0]="NoCertificate",l_[l_.NotEd25519=1]="NotEd25519",l_[l_.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",l_[l_.AltNameMismatch=3]="AltNameMismatch",l_[l_.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(c_||(c_={})),Gs.new(void 0,"net:peers"),Gs.new(void 0,"net"),Gs.new(void 0,"net"),Gs.new(void 0,"net"),Gs.new(void 0,"jamnps");const u_=h_(0);class d_ extends w{hash;slot;static Codec=we.Class(d_,{hash:we.bytes(Re).asOpaque(),slot:we.u32.asOpaque()});static create({hash:e,slot:t}){return new d_(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class g_{final;leafs;static Codec=we.Class(g_,{final:d_.Codec,leafs:we.sequenceVarLen(d_.Codec)});static create({final:e,leafs:t}){return new g_(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class f_ extends w{header;final;static Codec=we.Class(f_,{header:jr.Codec,final:d_.Codec});static create({header:e,final:t}){return new f_(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const p_=Gs.new(void 0,"protocol/up-0");class y_{getHandshake;onAnnouncement;kind=u_;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t){this.getHandshake=e,this.onAnnouncement=t}onStreamMessage(e,t){const r=e.streamId;if(!this.handshakes.has(r)){const s=ae.decodeObject(g_.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(p_.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(ge.encodeObject(g_.Codec,this.getHandshake()))))}const s=ae.decodeObject(f_.Codec,t);p_.info(`[${r}] got blocks announcement: ${s}`),this.onAnnouncement(s)}onClose(e){this.handshakes.delete(e)}sendHandshake(e,t){this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(ge.encodeObject(g_.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(ge.encodeObject(f_.Codec,t)):p_.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var m_;h_(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(m_||(m_={}));class b_ extends w{headerHash;direction;maxBlocks;static Codec=we.Class(b_,{headerHash:we.bytes(Re).asOpaque(),direction:we.u8.convert(e=>W(e),e=>{switch(e){case m_.AscExcl:return m_.AscExcl;case m_.DescIncl:return m_.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:we.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new b_(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}Gs.new(void 0,"protocol/ce-128");const A_=h_(129),I_=we.bytes(64).convert(e=>U.fromBlob(e.raw,64),e=>new Fi(e.raw));class v_ extends w{key;value;static Codec=we.Class(v_,{key:we.bytes(Vi),value:we.blob});static create({key:e,value:t}){return new v_(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class w_ extends w{keyValuePairs;static Codec=we.Class(w_,{keyValuePairs:we.sequenceVarLen(v_.Codec)});static create({keyValuePairs:e}){return new w_(e)}constructor(e){super(),this.keyValuePairs=e}}class S_ extends w{headerHash;startKey;endKey;maximumSize;static Codec=we.Class(S_,{headerHash:we.bytes(Re).asOpaque(),startKey:we.bytes(Vi),endKey:we.bytes(Vi),maximumSize:we.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new S_(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const E_=Gs.new(void 0,"protocol/ce-129");class C_{isServer;getBoundaryNodes;getKeyValuePairs;kind=A_;boundaryNodes=new Map;onResponse=new Map;constructor(e=!1,t,r){if(this.isServer=e,this.getBoundaryNodes=t,this.getKeyValuePairs=r,e&&(void 0===t||void 0===r))throw new Error("getBoundaryNodes and getKeyValuePairs are required in server mode.")}onStreamMessage(e,t){if(this.isServer){if(E_.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=ae.decodeObject(S_.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return E_.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(ge.encodeObject(we.sequenceVarLen(I_),s)),e.bufferAndSend(ge.encodeObject(w_.Codec,w_.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,ae.decodeObject(we.sequenceVarLen(I_),t)),void E_.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(ae.decodeObject(w_.Codec,t)),E_.info(`[${e.streamId}][client]: Received state values.`)}onClose(e){this.boundaryNodes.delete(e),this.onResponse.delete(e)}getStateByKey(e,t,r,s){if(this.onResponse.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");this.onResponse.set(e.streamId,s),e.bufferAndSend(ge.encodeObject(S_.Codec,S_.create({headerHash:t,startKey:r,endKey:r,maximumSize:X(4096)}))),e.close()}}h_(131),h_(132);class k_ extends w{epochIndex;ticket;static Codec=we.Class(k_,{epochIndex:we.u32.asOpaque(),ticket:vt.Codec});static create({epochIndex:e,ticket:t}){return new k_(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}Gs.new(void 0,"protocol/ce-131-ce-132"),h_(133);class x_ extends w{coreIndex;workPackage;static Codec=we.Class(x_,{coreIndex:we.u16.asOpaque(),workPackage:Rr.Codec});static create({coreIndex:e,workPackage:t}){return new x_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}Gs.new(void 0,"protocol/ce-133"),we.blob,h_(134);class B_ extends w{coreIndex;segmentsRootMappings;static Codec=we.Class(B_,{coreIndex:we.u16.asOpaque(),segmentsRootMappings:we.sequenceVarLen(Pr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new B_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class __ extends w{workReportHash;signature;static Codec=we.Class(__,{workReportHash:we.bytes(Re).asOpaque(),signature:we.bytes(sr).asOpaque()});static create({workReportHash:e,signature:t}){return new __(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}Gs.new(void 0,"protocol/ce-134"),h_(135);class R_ extends w{report;slot;signatures;static Codec=we.Class(R_,{report:Lr.Codec,slot:we.u32.asOpaque(),signatures:mt(e=>bt(Kr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new R_(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}Gs.new(void 0,"protocol/ce-135");const O_=t(import.meta.url)("node:net"),U_=t(import.meta.url)("node:path"),T_=t(import.meta.url)("node:buffer");var N_;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(N_||(N_={}));class D_{streamId;type;data;static Codec=we.Class(D_,{streamId:we.u32,type:we.u8.convert(e=>W(e),e=>{switch(e){case N_.Msg:return N_.Msg;case N_.Open:return N_.Open;case N_.Close:return N_.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:we.blob});static create({streamId:e,type:t,data:r}){return new D_(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class M_{streamByte;static Codec=we.Class(M_,{streamByte:we.u8});static create({streamByte:e}){return new M_(e)}constructor(e){this.streamByte=e}}const P_=Gs.new(void 0,"ext-ipc");class L_{streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;sender;constructor(e){const t={finished:!1};t.listen=new Promise((e,r)=>{t.resolve=e,t.reject=r}),this.onEnd=t,this.sender=new K_(e)}registerHandlers(...e){for(const t of e)this.streamHandlers.set(t.kind,t)}withStreamOfKind(e,t){for(const[r,s]of this.streams.entries())if(s.kind===e)return void t(s,new H_(r,this.sender));throw new Error(`Missing handler for ${e}!`)}withNewStream(e,t){const r=this.streamHandlers.get(e);if(void 0===r)throw new Error(`Stream with unregistered handler of kind: ${e} was requested to be opened.`);const s=this.streams,i=function e(){const t=Math.floor(65536*Math.random());return s.has(t)?e():t}();this.streams.set(i,r),this.pendingStreams.set(i,!0);const n=new H_(i,this.sender);n.open(M_.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=ae.decodeObject(D_.Codec,e),r=t.streamId;P_.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new H_(r,this.sender);if(void 0===s){if(t.type!==N_.Open)return void P_.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=ae.decodeObject(M_.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(P_.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===N_.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===N_.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||P_.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){P_.log(`Closing the handler. Reason: ${void 0!==e?e.message:"close"}.`);for(const[t,r]of this.streams.entries())r.onClose(t,void 0===e);this.streams.clear(),this.onEnd.finished=!0,void 0!==e?this.onEnd.reject(e):this.onEnd.resolve()}waitForEnd(){return P_.log("Waiting for the handler to be closed."),this.onEnd.listen}}class H_{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=ge.encodeObject(M_.Codec,e);this.sender.send(ge.encodeObject(D_.Codec,D_.create({streamId:this.streamId,type:N_.Open,data:t})))}bufferAndSend(e){return this.sender.send(ge.encodeObject(D_.Codec,D_.create({streamId:this.streamId,type:N_.Msg,data:e}))),!0}close(){this.sender.send(ge.encodeObject(D_.Codec,D_.create({streamId:this.streamId,type:N_.Close,data:O.blobFromNumbers([])})))}}class K_{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(V_);ge.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const V_=4;function Q_(e){const t=function(e){const t=new An.EventEmitter;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=d_.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",f_.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===xs.platform()?"\\\\.\\pipe\\typeberry":U_.join(xs.tmpdir(),"typeberry.ipc"),n=Gs.new(void 0,"ext-ipc"),o=(0,O_.createServer)(i=>{n.log("Client connected");const o=new L_(i);o.registerHandlers(new y_(t,()=>{})),o.registerHandlers(new C_(!0,r,s));const a=e=>{if(!(e instanceof f_))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(u_,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=T_.Buffer.alloc(0),r=-1;return s=>{t=T_.Buffer.concat([t,s]);do{if(-1===r){if(t.length<V_)break;r=t.readUint32LE(),t=t.subarray(V_)}if(t.length<r)break;const s=t.subarray(0,r);t=t.subarray(r),r=-1,e(s)}while(t.length>0)}}(e=>{try{o.onSocketMessage(new Uint8Array(e))}catch(e){n.error(`Received invalid data on socket: ${e}. Closing connection.`),i.end()}})),i.on("end",()=>{n.log("Client disconnected"),o.onClose({}),e.off("annoucement",a)}),i.on("error",e=>{n.error(`Socket error: ${e}`),o.onClose({error:e}),i.end()})});try{Cs.unlinkSync(i)}catch{}const a=new AbortController;return o.listen({path:i,signal:a.signal},()=>{n.log(`IPC server is listening at ${i}`)}),o.on("error",e=>{throw e}),()=>{n.info("Closing IPC server."),o.close(),a.abort(),o.unref()}}(t,()=>{const e=r??d_.create({hash:U.zero(Re).asOpaque(),slot:gr(0)});return g_.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=O.blobFromNumbers([255,255,0,0]);return U.fromBlob(Ke("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,Vi),Vi).isEqualTo(t)&&(r=O.blobFromNumbers([255,255,255,0])),[new v_(t,r)]})}(e);return()=>{t()}}const F_=e=>e.endsWith(".json");function G_(e,t){const r=ks().readFileSync(e),s=O.blobFrom(new Uint8Array(r));return ae.decodeObject(Zr.Codec.View,s,t)}function $_(e,t){const r=ks().readFileSync(e,"utf-8"),s=j(JSON.parse(r),(i=t,z.object({header:ws,extrinsic:(n=i,z.object({tickets:ms,preimages:ps,guarantees:gs,assurances:ar(n),disputes:ss},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>Yr.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>Zr.create({header:e,extrinsic:t}))));var i,n;const o=ge.encodeObject(Zr.Codec,s,t);return ae.decodeObject(Zr.Codec.View,o,t)}const j_={genesisPath:"",timeSlot:gr(0),validatorIndex:fr(0)};class q_{isAuthoring;blocksToImport;nodeName;node;dev;static new({isAuthoring:e,blockToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n}){let o=i??{...j_};return void 0!==n&&(o={...o,...n}),new q_(e??!1,t??[],r,s,o)}constructor(e,t,r,s,i){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i}}const z_=Gs.new(void 0,"jam");var W_;async function J_(e,t){if(!$s.isMainThread)return void z_.error("The main binary cannot be running as a Worker!");const r=X_(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=Ke(e).toString().substring(2,10),n=He(t).asOpaque(),o=`${r}/${i}/${n.toString().substring(2,10)}`;z_.info(`🛢️ Opening database at ${o}`);try{return{dbPath:o,rootDb:new mn(o,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${o}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new gn(e,r),n=new bn(e,r),o=i.getBestHeaderHash(),a=i.getPostStateRoot(o);if(z_.log(`🛢️ Best header hash: ${o}`),z_.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(U.zero(Re))&&!o.isEqualTo(U.zero(Re)))return void await r.db.close();z_.log("🛢️ Database looks fresh. Initializing.");const c=ae.decodeObject(jr.Codec,s.genesisHeader,e),l=Zr.create({header:jr.empty(),extrinsic:Yr.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,h=Zr.create({header:c,extrinsic:l}),u=ae.decodeObject(Zr.Codec.View,ge.encodeObject(Zr.Codec,h,e),e);z_.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:d,genesisStateRootHash:g}=function(e,t){const r=hn.fromEntries(Array.from(t.entries())),s=en.fromTruncatedDictionaryUnsafe(r),i=Hi.fromStateEntries(e,s),n=s.getRootHash();return z_.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new Oe(t,u)),await n.insertState(t,d),await i.setPostStateRoot(t,g),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const o=await async function(){const e=vh,t=new Ah;return Mn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),a=Q_({bestHeader:o.getState("ready(main)").onBestBlock}),c=new yt(r,i,e.node.authorship.omitSealVerification),l=o.transition((e,t)=>e.sendConfig(t,c)),h=Z_(l,r,e.blocksToImport),u=await Y_(e.isAuthoring,c,l);z_.info("[main]⌛ waiting for importer to finish");const d=await h;z_.log("[main] ☠️ Closing the extensions"),a(),z_.log("[main]⌛ waiting for tasks to finish"),await d.currentState().waitForWorkerToFinish(),z_.log("[main] ☠️ Closing the authorship module"),u(),z_.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(W_||(W_={}));const Y_=async(e,t,r)=>{if(!e)return()=>Promise.resolve();z_.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=Bh,t=new kh;return Mn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/block-generator/index.ts"),e,"ready(main)",t)}()).transition((t,r)=>t.sendConfig(r,e));return{generator:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(t);return r.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{z_.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},Z_=async(e,t,r)=>null===r?e.waitForState("finished"):(z_.info(`📖 Reading ${r.length} blocks`),e.transition((e,s)=>{const i=function*(e){const{chainSpec:t}=e;for(const r of e.files){const e=F_(r)?$_(r,t):G_(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)z_.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return z_.info("All blocks scheduled to be imported."),e.finish(s)})),X_=e=>{if(e===Ts.Full)return pt;if(e===Ts.Tiny)return ft;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[Ts.Full,Ts.Tiny]}`)},eR=(e=>{var t={};return o.d(t,e),t})({default:()=>s.default}),tR=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${Us.name}]\n --config Path to a config file or '${Os}'.\n [default: ${Us.config}]\n`;var rR;function sR(e,t){const{name:r}=nR(e,"name",e=>e,Us.name),{config:s}=nR(e,"config",e=>e===Os?Os:t(e),Us.config);return{nodeName:r,configPath:s}}function iR(e,t){const r=(0,eR.default)(e),s=r._.shift()??rR.Run;switch(s){case rR.Run:{const e=sR(r,t);return oR(r),{command:rR.Run,args:e}}case rR.Import:{const e=sR(r,t),s=r._.map(e=>t(e));return r._=[],oR(r),{command:rR.Import,args:{...e,files:s}}}default:r._.unshift(s),oR(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function nR(e,t,r,s){const i=e[t];if(void 0===i)return{[t]:s};if(delete e[t],"string"!=typeof i)throw new Error(`Option '--${t}' requires an argument.`);try{const e=r(i);return{[t]:e??s}}catch(e){throw new Error(`Invalid value '${i}' for option '${t}': ${e}`)}}function oR(e){const t=Object.keys(e).filter(e=>"_"!==e&&"--"!==e);if(e._.length>0)throw new Error(`Unexpected command: '${e._[0]}'`);if((e["--"]?.length??0)>0)throw new Error(`Unexpected parameters: '${e["--"]?.[0]}'...`);if(t.length>0)throw new Error(`Unrecognized options: '${t}'`)}!function(e){e.Run="run",e.Import="import"}(rR||(rR={}));const aR=e=>{const t=e.command===rR.Import?e.args.files:[],r=function(e){if(e===Os)return j(_s,Ds.fromJson);try{const t=ks().readFileSync(e,"utf8");return j(JSON.parse(t),Ds.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath);return q_.new({isAuthoring:!1,blockToImport:t,nodeName:e.args.nodeName,nodeConfig:r})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,c.pathToFileURL)(process.argv[1]).href){Gs.configureAll(process.env.JAM_LOG??"",Ms.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=iR(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(tR),process.exit(1)}J_(aR(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let cR;Gs.configureAll(process.env.JAM_LOG??"",Ms.LOG);try{cR=iR(process.argv.slice(2),lR)}catch(e){console.error(`\n${e}\n`),console.info(tR),process.exit(1)}function lR(e){return e}J_(aR(cR),lR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{rR as Command,tR as HELP,iR as parseArgs,aR as prepareConfigFile};
2
+ import{fileURLToPath as e}from"node:url";import{createRequire as t}from"node:module";import*as r from"lmdb";import*as s from"minimist";var i={8:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.matchingBitCount=t.intLog2=t.cidrPrefixToMaskBinaryString=t.leftPadWithZeroBit=t.dottedDecimalNotationToBinaryString=t.parseBinaryStringToBigInt=t.decimalNumberToOctetString=t.numberToBinaryString=void 0,t.numberToBinaryString=e=>e.toString(2),t.decimalNumberToOctetString=e=>{let r=t.numberToBinaryString(e);if(r.length>8)throw new Error("Given decimal in binary contains digits greater than an octet");return t.leftPadWithZeroBit(r,8)},t.parseBinaryStringToBigInt=e=>BigInt(`0b${e}`),t.dottedDecimalNotationToBinaryString=e=>e.split(".").reduce((e,r)=>e.concat(t.decimalNumberToOctetString(parseInt(r))),""),t.leftPadWithZeroBit=(e,t)=>{if(e.length>t)throw new Error(`Given string is already longer than given final length after padding: ${t}`);return"0".repeat(t-e.length).concat(e)},t.cidrPrefixToMaskBinaryString=(e,t)=>{let r;if(r="IPv4"==t?32:128,e>r)throw Error(`Value is greater than ${r}`);return`${"1".repeat(e)}${"0".repeat(r-e)}`},t.intLog2=e=>{let t=0;for(;e%2n==0n;){if(2n===e){t++;break}if((e>>=1n)%2n!=0n){t=0;break}t++}if(0==t)throw new Error(`The value of log2 for ${e.toString()} is not an integer`);return t},t.matchingBitCount=(e,t)=>{let r,s;e.length>=t.length?(r=e,s=t):(r=t,s=e);let i=0;for(;i<r.length&&r.charAt(i)===s.charAt(i);i++);return i}},54:e=>{e.exports=function e(r,s){if(!r){var i=new t(s);throw Error.captureStackTrace&&Error.captureStackTrace(i,e),i}};class t extends Error{}t.prototype.name="AssertionError"},154:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Hexadecatet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e,16):parseInt(String(e),16);let[r,i]=s.Validator.isValidIPv6Hexadecatet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(16)}}t.Hexadecatet=i},212:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4=t.IPv6Mask=t.IPv4Mask=t.IPv6=t.Asn=t.IPv4=t.AbstractIPNum=void 0;const s=r(301),i=r(660),n=r(8),o=r(8),a=r(8),c=r(8),l=r(154),h=r(984),u=r(872),d=r(984);class g{getValue(){return this.value}toBinaryString(){return a.leftPadWithZeroBit(this.value.toString(2),this.bitSize)}hasNext(){return this.value<this.maximumBitSize}hasPrevious(){return this.value>0n}isEquals(e){return this.value===e.value}isLessThan(e){return this.value<e.value}isGreaterThan(e){return this.value>e.value}isLessThanOrEquals(e){return this.value<=e.value}isGreaterThanOrEquals(e){return this.value>=e.value}}t.AbstractIPNum=g;class f extends g{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="IPv4",this.octets=[],this.separator=".","string"==typeof e){let[t,r]=this.constructFromDecimalDottedString(e);this.value=t,this.octets=r}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.octets=r}}static fromNumber(e){return new f(e)}static fromDecimalDottedString(e){return new f(e)}static fromString(e){return f.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new f(o.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return f.fromNumber(this.getValue()+1n)}previousIPNumber(){return f.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return y.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[o,a]=i.Validator.isValidIPv4String(e);if(!o)throw new Error(a.filter(e=>""!==e).toString());return t=e.split(".").map(e=>s.Octet.fromString(e)),r=BigInt(`0b${n.dottedDecimalNotationToBinaryString(e)}`),[r,t]}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv4Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e="bigint"==typeof e?e:BigInt(e),this.binaryStringToDecimalOctets(s)]}binaryStringToDecimalOctets(e){return e.length<32&&(e=a.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(o.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=f;class p extends g{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)p.startWithASPrefix(e)?this.value=BigInt(parseInt(e.substring(2))):-1!=e.indexOf(".")?this.value=BigInt(this.parseFromDotNotation(e)):this.value=BigInt(parseInt(e));else{let t=BigInt(e),[r,s]=i.Validator.isValidAsnNumber(t);if(!r)throw Error(s.filter(e=>""!==e).toString());this.value=t}}static fromString(e){return new p(e)}static fromNumber(e){return new p(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${p.AS_PREFIX}${e}`}toASPlain(){return this.value.toString()}toASDot(){return this.value.valueOf()>=65536n?this.toASDotPlus():this.toASPlain()}toASDotPlus(){let e=this.value.valueOf()/65535n;return`${e}.${this.value.valueOf()%65535n-e}`}toBinaryString(){return c.numberToBinaryString(this.value)}is16Bit(){let[e]=i.Validator.isValid16BitAsnNumber(this.value);return e}is32Bit(){return!this.is16Bit()}nextIPNumber(){return new p(this.value.valueOf()+1n)}previousIPNumber(){return new p(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(p.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=p,p.AS_PREFIX="AS";class y extends g{constructor(e){if(super(),this.bitSize=128,this.maximumBitSize=i.Validator.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE,this.type="IPv6",this.hexadecatet=[],this.separator=":","string"==typeof e){let t=u.expandIPv6Number(e),[r,s]=this.constructFromHexadecimalDottedString(t);this.value=r,this.hexadecatet=s}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.hexadecatet=r}}static fromBigInt(e){return new y(e)}static fromHexadecatet(e){return new y(e)}static fromString(e){return y.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=a.leftPadWithZeroBit(e,128);return new y(o.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new f(e).toIPv4MappedIPv6()}toString(){let e=this.hexadecatet.map(e=>e.toString()).join(":");return this.hexadecatet.length<8?"::"+e:e}getHexadecatet(){return this.hexadecatet}nextIPNumber(){return y.fromBigInt(this.getValue()+1n)}previousIPNumber(){return y.fromBigInt(this.getValue()-1n)}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv6Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e,this.binaryStringToHexadecatets(s)]}constructFromHexadecimalDottedString(e){let[t,r]=i.Validator.isValidIPv6String(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=e.split(":").map(e=>l.Hexadecatet.fromString(e));return[BigInt(`0b${d.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=h.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=y;class m extends f{constructor(e){let t,r;if(super(e),this.octets=[],[t,r]=i.Validator.isValidIPv4Mask(e),!t)throw new Error(r.filter(e=>""!==e).toString());let o=e.split(".");this.octets=o.map(e=>s.Octet.fromString(e));let a=n.dottedDecimalNotationToBinaryString(e);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class b extends y{constructor(e){let t,r;super(e),this.hexadecatet=[];let s=u.expandIPv6Number(e);if([t,r]=i.Validator.isValidIPv6Mask(s),!t)throw new Error(r.filter(e=>""!==e).toString());let n=s.split(":");this.hexadecatet=n.map(e=>l.Hexadecatet.fromString(e));let o=d.hexadectetNotationToBinaryString(s);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`),this.value=BigInt(`0b${d.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new b(e)}}t.IPv6Mask=b,t.isIPv4=function(e){return 32===e.bitSize}},259:e=>{var t,r,s=(()=>{for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return t=>{for(var r=t.length,s=new Uint8Array(3*(r-("="==t[r-1])-("="==t[r-2]))/4|0),i=0,n=0;i<r;){var o=e[t.charCodeAt(i++)],a=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=o<<2|a>>4,s[n++]=a<<4|c>>2,s[n++]=c<<6|l}return s}})(),i=(t={"wasm-binary:./blake2b.wat"(e,t){t.exports=s("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=")}},function(){return r||(0,t[Object.keys(t)[0]])((r={exports:{}}).exports,r),r.exports})(),n=WebAssembly.compile(i);e.exports=async e=>(await WebAssembly.instantiate(await n,e)).exports},287:e=>{function t(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}e.exports={isBuffer:function(e){return Buffer.isBuffer(e)||e instanceof Uint8Array},isEncoding:function(e){return Buffer.isEncoding(e)},alloc:function(e,t,r){return Buffer.alloc(e,t,r)},allocUnsafe:function(e){return Buffer.allocUnsafe(e)},allocUnsafeSlow:function(e){return Buffer.allocUnsafeSlow(e)},byteLength:function(e,t){return Buffer.byteLength(e,t)},compare:function(e,t){return Buffer.compare(e,t)},concat:function(e,t){return Buffer.concat(e,t)},copy:function(e,r,s,i,n){return t(e).copy(r,s,i,n)},equals:function(e,r){return t(e).equals(r)},fill:function(e,r,s,i,n){return t(e).fill(r,s,i,n)},from:function(e,t,r){return Buffer.from(e,t,r)},includes:function(e,r,s,i){return t(e).includes(r,s,i)},indexOf:function(e,r,s,i){return t(e).indexOf(r,s,i)},lastIndexOf:function(e,r,s,i){return t(e).lastIndexOf(r,s,i)},swap16:function(e){return t(e).swap16()},swap32:function(e){return t(e).swap32()},swap64:function(e){return t(e).swap64()},toBuffer:t,toString:function(e,r,s,i){return t(e).toString(r,s,i)},write:function(e,r,s,i,n){return t(e).write(r,s,i,n)},writeDoubleLE:function(e,r,s){return t(e).writeDoubleLE(r,s)},writeFloatLE:function(e,r,s){return t(e).writeFloatLE(r,s)},writeUInt32LE:function(e,r,s){return t(e).writeUInt32LE(r,s)},writeInt32LE:function(e,r,s){return t(e).writeInt32LE(r,s)},readDoubleLE:function(e,r){return t(e).readDoubleLE(r)},readFloatLE:function(e,r){return t(e).readFloatLE(r)},readUInt32LE:function(e,r){return t(e).readUInt32LE(r)},readInt32LE:function(e,r){return t(e).readInt32LE(r)}}},301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Octet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e):e;let[r,i]=s.Validator.isValidIPv4Octet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(10)}}t.Octet=i},405:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o=null;function a(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return a().set(e,r/1),c=e.length,r}let h=null;function u(){return null!==h&&0!==h.byteLength||(h=new Int32Array(n.memory.buffer)),h}function d(e,t){return e>>>=0,a().subarray(e/1,e/1+t)}t.exports.hc=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),o=l(e,n.__wbindgen_malloc),a=c;n.ring_commitment(i,o,a);var t=u()[i/4+0],r=u()[i/4+1],s=d(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.KG=function(e,t,r,s,i){try{const g=n.__wbindgen_add_to_stack_pointer(-16),f=l(e,n.__wbindgen_malloc),p=c,y=l(r,n.__wbindgen_malloc),m=c,b=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(g,f,p,t,y,m,b,A,I,v);var o=u()[g/4+0],a=u()[g/4+1],h=d(o,a).slice();return n.__wbindgen_free(o,1*a,1),h}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.ZJ=function(e,t,r){try{const a=n.__wbindgen_add_to_stack_pointer(-16),h=l(e,n.__wbindgen_malloc),g=c,f=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(a,h,g,f,p,r);var s=u()[a/4+0],i=u()[a/4+1],o=d(s,i).slice();return n.__wbindgen_free(s,1*i,1),o}finally{n.__wbindgen_add_to_stack_pointer(16)}};const g=s(928).join(i,"bandersnatch_bg.wasm"),f=s(896).readFileSync(g),p=new WebAssembly.Module(f),y=new WebAssembly.Instance(p,{});n=y.exports},412:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4CidrRange=t.IPv6CidrRange=t.IPv4CidrRange=t.AbstractIPRange=t.RangedSet=void 0;const s=r(212),i=r(516),n=r(8),o=r(660);class a{constructor(e,t){if(this.first=e,this.last=t,e.isGreaterThan(t))throw new Error(`${e.toString()} should be lower than ${t.toString()}`);this.currentValue=e,this.bitValue=BigInt(e.bitSize)}static fromSingleIP(e){return new a(e,e)}static fromCidrRange(e){return new a(e.getFirst(),e.getLast())}static fromRangeString(e){let t=e.split("-").map(e=>e.trim());if(2!==t.length)throw new Error("Argument should be in the format firstip-lastip");let[r,i]=t,[n]=o.Validator.isValidIPv4String(r),[c]=o.Validator.isValidIPv4String(i),[l]=o.Validator.isValidIPv6String(r),[h]=o.Validator.isValidIPv6String(i);if(n&&c)return new a(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&h)return new a(s.IPv6.fromHexadecatet(r),s.IPv6.fromHexadecatet(i));throw new Error("First IP and Last IP should be valid and same type")}getFirst(){return this.first}getLast(){return this.last}getSize(){return this.last.getValue()-this.first.getValue()+1n}toRangeString(){return`${this.getFirst()}-${this.getLast()}`}inside(e){return e.contains(this)}contains(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return t.isLessThanOrEquals(s)&&r.isGreaterThanOrEquals(i)}isEquals(e){return this.getFirst().isEquals(e.getFirst())&&this.getLast().isEquals(e.getLast())}isLessThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()<e.getSize():this.getFirst().isLessThan(e.getFirst()))}isGreaterThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()>e.getSize():this.getFirst().isGreaterThan(e.getFirst()))}isOverlapping(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.isGreaterThan(s)&&r.isLessThanOrEquals(i)&&t.isLessThan(s)||i.isGreaterThan(t)&&i.isLessThanOrEquals(r)&&s.isLessThan(t)}isCidrAble(){if(1n===this.getSize())return!0;try{let e=n.intLog2(this.getSize()),t=n.parseBinaryStringToBigInt(n.cidrPrefixToMaskBinaryString(e,s.isIPv4(this.currentValue)?"IPv4":"IPv6"));return this.first.getValue()===(t&this.first.getValue())}catch(e){return!1}}toCidrRange(){return s.isIPv4(this.currentValue)?this.toIPv4CidrRange():this.toIPv6CidrRange()}isConsecutive(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.hasNext()&&r.nextIPNumber().isEquals(s)||i.hasNext()&&i.nextIPNumber().isEquals(t)}union(e){if(this.isEquals(e))return new a(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new a(this.getFirst(),e.getLast()):new a(e.getFirst(),this.getLast());if(this.contains(e))return new a(this.getFirst(),this.getLast());if(e.contains(this))return new a(e.getFirst(),e.getLast());throw new Error("Ranges do not overlap nor are equal")}prepend(e){if(e.getLast().nextIPNumber().isEquals(this.getFirst()))return new a(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new a(this.getFirst(),e.getLast());throw new Error("Range to append must be adjacent")}subtract(e){if(!this.isOverlapping(e))throw new Error("Cannot subtract ranges that are not overlapping");if(!this.isLessThan(e))throw new Error("Cannot subtract a larger range from this range");return new a(this.getFirst(),e.getLast())}takeSubRange(e,t){if(e+t>this.getSize())throw new RangeError("Requested range is greater than what can be taken");if(0n===t)throw new Error("Sub range cannot be zero");let r=this.getFirst().value+e,i=s.isIPv4(this.getFirst())?s.IPv4.fromNumber(r):s.IPv6.fromBigInt(r),n=i.value+(t-1n),o=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new a(i,o)}difference(e){if(e.getSize()>this.getSize())throw new Error("Range is greater than range to be subtracted from");if(!this.contains(e))throw new Error("Range to subtract is not contained in this range");let t=[];try{t.push(new a(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new a(e.getLast().nextIPNumber(),this.getLast()))}catch(e){}return t}*take(e){let t=this.getFirst(),r=void 0===e?this.getSize().valueOf():e;for(;r>0;)r--,yield t,t=t.nextIPNumber()}*[Symbol.iterator](){yield*this.take()}toIPv4CidrRange(){let e=new l(s.IPv4.fromNumber(this.getFirst().getValue()),i.IPv4Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}toIPv6CidrRange(){let e=new h(s.IPv6.fromBigInt(this.getFirst().getValue()),i.IPv6Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}}t.RangedSet=a;class c{hasNextRange(){let e=this.getSize();return 2n**this.bitValue-e>=this.getFirst().getValue()+e}hasPreviousRange(){return this.getSize()<=this.getFirst().getValue()}toRangeSet(){return new a(this.getFirst(),this.getLast())}inside(e){return this.toRangeSet().inside(e.toRangeSet())}contains(e){return this.toRangeSet().contains(e.toRangeSet())}toRangeString(){return this.toRangeSet().toRangeString()}isOverlapping(e){return this.toRangeSet().isOverlapping(e.toRangeSet())}isConsecutive(e){return this.toRangeSet().isConsecutive(e.toRangeSet())}isCidrMergeable(e){const t=BigInt(n.matchingBitCount(this.getFirst().toBinaryString(),e.getFirst().toBinaryString()));return this.getPrefix().value-t===1n&&this.isConsecutive(e)&&this.getSize()===e.getSize()}isMergeable(e){return this.isCidrMergeable(e)||this.contains(e)||this.inside(e)}isEquals(e){return this.toRangeSet().isEquals(e.toRangeSet())}merge(e){if(!this.isCidrMergeable(e))throw new Error(`Cannot merge. Ranges (${this.toRangeString()},${e.toRangeString()}) are not consecutive and/or of same size`);return this.newInstance(this.getFirst(),this.getPrefix().merge())}*takeStream(e){return this.toRangeSet().take(e)}*[Symbol.iterator](){yield*this.toRangeSet()}}t.AbstractIPRange=c;class l extends c{constructor(e,t){super(),this.ipv4=e,this.cidrPrefix=t,this.bitValue=32n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(a),i.IPv4Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv4.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv4.fromNumber(this.ipv4.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv4)}newInstance(e,t){return new l(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize()){let t=o.Validator.takeOutOfRangeSizeMessage.replace("$count",e.toString()).replace("$size",this.getSize().toString());throw new Error(t)}for(let s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(32n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv4Prefix.fromNumber(e+1n),r=this.getFirst(),s=new l(r,t),n=s.getLast().nextIPNumber();return[s,new l(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new l(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new l(new s.IPv4(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new l(new s.IPv4(t),this.cidrPrefix)}}}t.IPv4CidrRange=l;class h extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new h(s.IPv6.fromHexadecatet(a),i.IPv6Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv6.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv6.fromBigInt(this.ipv6.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv6)}newInstance(e,t){return new h(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize())throw new Error(`${e.toString()} is greater than ${this.getSize().toString()}, the size of the range`);for(var s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(128n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv6Prefix.fromNumber(e+1n),r=this.getFirst(),s=new h(r,t),n=s.getLast().nextIPNumber();return[s,new h(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new h(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new h(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new h(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=h;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),o=e.cidrPrefix.toMask().getValue(),a=n.leftPadWithZeroBit((o^i).toString(2),r);return d(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(a)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(a))};function d(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=d},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},516:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4Prefix=t.IPv6Prefix=t.IPv4Prefix=void 0;const s=r(660),i=r(212),n=r(8),o=r(984),a=r(154);class c{constructor(e){let t,r;if(this.type="IPv4",this.bitValue=32n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv4"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new c(e)}static fromRangeSize(e){let t=1n===e?32:32-h(e,s.Validator.IPV4_SIZE);return c.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(Number(32n-this.value));return i.IPv4Mask.fromDecimalDottedString(this.toDecimalNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new c(this.value-1n)}split(){return new c(this.value+1n)}toDecimalNotation(e){return`${n.parseBinaryStringToBigInt(e.substr(0,8))}.${n.parseBinaryStringToBigInt(e.substr(8,8))}.${n.parseBinaryStringToBigInt(e.substr(16,8))}.${n.parseBinaryStringToBigInt(e.substr(24,8))}`}}t.IPv4Prefix=c;class l{constructor(e){let t,r;if(this.type="IPv6",this.bitValue=128n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv6"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new l(e)}static fromRangeSize(e){let t=1n===e?128:128-h(e,s.Validator.IPV6_SIZE);return l.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(128-Number(this.value));return i.IPv6Mask.fromHexadecatet(this.toHexadecatetNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new l(this.value-1n)}split(){return new l(this.value+1n)}toHexadecatetNotation(e){return e.match(/.{1,16}/g).map(e=>a.Hexadecatet.fromString(o.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function h(e,t){let r=t>s.Validator.IPV4_SIZE?"IPv6":"IPv4";if(e>t||0n===e)throw new Error(s.Validator.invalidIPRangeSizeMessage.replace("$iptype",r));try{return n.intLog2(e)}catch(e){throw new Error(s.Validator.invalidIPRangeSizeForCidrMessage)}}t.IPv6Prefix=l,t.isIPv4Prefix=function(e){return"IPv4"===e.type}},578:(e,t,r)=>{var s=r(54),i=r(287),n=null,o="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),a=64,c=[];e.exports=p;var l=e.exports.BYTES_MIN=16,h=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),d=e.exports.KEYBYTES_MAX=64,g=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),f=e.exports.PERSONALBYTES=16;function p(e,t,r,i,o){if(!(this instanceof p))return new p(e,t,r,i,o);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==o&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=h,"digestLength must be at most "+h+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=u,"key must be at least "+u+", was given "+t.length),s(t.length<=d,"key must be at least "+d+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===g,"salt must be exactly "+g+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===f,"personal must be exactly "+f+", was given "+i.length))),c.length||(c.push(a),a+=216),this.digestLength=e,this.finalized=!1,this.pointer=c.pop(),this._memory=new Uint8Array(n.memory.buffer),this._memory.fill(0,0,64),this._memory[0]=this.digestLength,this._memory[1]=t?t.length:0,this._memory[2]=1,this._memory[3]=1,r&&this._memory.set(r,32),i&&this._memory.set(i,48),this.pointer+216>this._memory.length&&this._realloc(this.pointer+216),n.blake2b_init(this.pointer,this.digestLength),t&&(this.update(t),this._memory.fill(0,a,a+t.length),this._memory[this.pointer+200]=128)}function y(){}p.prototype._realloc=function(e){n.memory.grow(Math.max(0,Math.ceil(Math.abs(e-this._memory.length)/65536))),this._memory=new Uint8Array(n.memory.buffer)},p.prototype.update=function(e){return s(!1===this.finalized,"Hash instance finalized"),s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),a+e.length>this._memory.length&&this._realloc(a+e.length),this._memory.set(e,a),n.blake2b_update(this.pointer,a,a+e.length),this},p.prototype.digest=function(e){if(s(!1===this.finalized,"Hash instance finalized"),this.finalized=!0,c.push(this.pointer),n.blake2b_final(this.pointer),!e||"binary"===e)return this._memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if("string"==typeof e)return i.toString(this._memory,e,this.pointer+128,this.pointer+128+this.digestLength);s(e instanceof Uint8Array&&e.length>=this.digestLength,"input must be Uint8Array or Buffer");for(var t=0;t<this.digestLength;t++)e[t]=this._memory[this.pointer+128+t];return e},p.prototype.final=p.prototype.digest,p.WASM=n,p.SUPPORTED="undefined"!=typeof WebAssembly,p.ready=function(e){return e||(e=y),o?o.then(()=>e(),e):e(new Error("WebAssembly not supported"))},p.prototype.ready=p.ready,p.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},p.prototype.setPartialHash=function(e){this._memory.set(e,this.pointer)}},618:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||t.hasOwnProperty(r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(8),t),i(r(154),t),i(r(984),t),i(r(212),t),i(r(429),t),i(r(951),t),i(r(412),t),i(r(872),t),i(r(301),t),i(r(516),t),i(r(660),t)},625:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o={};o.__wbindgen_placeholder__=t.exports;let a=null;function c(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let l=0;function h(e,t){const r=t(1*e.length,1)>>>0;return c().set(e,r/1),l=e.length,r}t.exports.verify_ed25519=function(e){const t=h(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,o,a=(i=s[0],o=s[1],i>>>=0,c().subarray(i/1,i/1+o)).slice();return n.__wbindgen_free(s[0],1*s[1],1),a},t.exports.verify_ed25519_batch=function(e){const t=h(e,n.__wbindgen_malloc),r=l;return 0!==n.verify_ed25519_batch(t,r)},t.exports.__wbindgen_init_externref_table=function(){const e=n.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)};const u=s(928).join(i,"ed25519_wasm_bg.wasm"),d=s(896).readFileSync(u),g=new WebAssembly.Module(d),f=new WebAssembly.Instance(g,o);n=f.exports,t.exports.__wasm=n,n.__wbindgen_start()},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Validator=void 0;const s=r(8),i=r(8),n=r(872),o=r(984),a=r(984);class c{static isWithinRange(e,t,r){return e>=t&&e<=r}static isValidAsnNumber(e){let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return[t,t?[]:[c.invalidAsnRangeMessage]]}static isValid16BitAsnNumber(e){let t=c.isWithinRange(e,0n,c.SIXTEEN_BIT_SIZE);return[t,t?[]:[c.invalid16BitAsnRangeMessage]]}static isValidIPv4Number(e){e="bigint"==typeof e?e:BigInt(e);let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv4NumberMessage]]}static isValidIPv6Number(e){let t=this.isWithinRange(e,0n,this.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv6NumberMessage]]}static isValidIPv4Octet(e){let t=this.isWithinRange(e,0n,this.EIGHT_BIT_SIZE);return[t,t?[]:[c.invalidOctetRangeMessage]]}static isValidIPv6Hexadecatet(e){let t=this.isWithinRange(e,0n,this.SIXTEEN_BIT_SIZE);return t?[t,[]]:[t,[c.invalidHexadecatetMessage]]}static isValidIPv4String(e){let t=e.split(".");if(4!=t.length||t.includes(""))return[!1,[c.invalidOctetCountMessage]];let r=t.every(e=>!!c.isNumeric(e)&&c.isValidIPv4Octet(BigInt(e))[0]);return r?(r=c.IPV4_PATTERN.test(e),[r,r?[]:[c.invalidIPv4PatternMessage]]):[!1,[c.invalidOctetRangeMessage]]}static isValidIPv6String(e){try{let t=n.expandIPv6Number(e).split(":");if(8!=t.length)return[!1,[c.invalidHexadecatetCountMessage]];let r=t.every(e=>!!c.isHexadecatet(e)&&c.isValidIPv6Hexadecatet(BigInt(`0x${e}`))[0]);return r?(r=c.IPV6_PATTERN.test(e),[r,r?[]:[c.invalidIPv6PatternMessage]]):[!1,[c.invalidHexadecatetMessage]]}catch(e){return[!1,[e]]}}static isValidPrefixValue(e,t){if("IPv4"===t){let t=c.isWithinRange(BigInt(e),0n,32n);return[t,t?[]:[c.invalidPrefixValueMessage]]}if("IPv6"===t){let t=c.isWithinRange(BigInt(e),0n,128n);return[t,t?[]:[c.invalidPrefixValueMessage]]}return[!1,[c.invalidInetNumType]]}static isValidIPv4Mask(e){let t=s.dottedDecimalNotationToBinaryString(e),r=c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv6Mask(e){let t=a.hexadectetNotationToBinaryString(e),r=c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv4CidrNotation(e){let t=e.split("/");if(2!==t.length||0===t[0].length||0===t[1].length)return[!1,[c.invalidIPv4CidrNotationMessage]];let r=t[0],s=t[1];if(isNaN(Number(s)))return[!1,[c.invalidIPv4CidrNotationMessage]];let[i,n]=c.isValidIPv4String(r),[o,a]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&o,h=n.concat(a);return l?[l,[]]:[l,h]}static isValidIPv4CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv4CidrNotation,s.dottedDecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv4"))}static isValidIPv6CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv6CidrNotation,o.colonHexadecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv6"))}static isValidCidrRange(e,t,r,s){let i=t(e);if(!i[0])return i;let n=e.split("/"),o=n[0],a=n[1],l=BigInt(`0b${r(o)}`),h=(l&BigInt(`0b${s(parseInt(a))}`))===l;return h?[h,[]]:[h,[c.InvalidIPCidrRangeMessage]]}static isValidIPv4RangeString(e){return this.isValidRange(e,c.isValidIPv4String,(e,t)=>BigInt(`0b${s.dottedDecimalNotationToBinaryString(e)}`)>=BigInt(`0b${s.dottedDecimalNotationToBinaryString(t)}`))}static isValidIPv6RangeString(e){return this.isValidRange(e,c.isValidIPv6String,(e,t)=>BigInt(`0b${a.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${a.hexadectetNotationToBinaryString(t)}`))}static isValidRange(e,t,r){let s=e.split("-").map(e=>e.trim());if(2!==s.length||0===s[0].length||0===s[1].length)return[!1,[c.invalidRangeNotationMessage]];let i=s[0],n=s[1],[o,a]=t(i),[l,h]=t(n),u=o&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let d=a.concat(h);return u?[u,[]]:[u,d]}static isValidIPv6CidrNotation(e){let t=c.IPV6_RANGE_PATTERN.test(e);return t?[t,[]]:[t,[c.invalidIPv6CidrNotationString]]}static isValidBinaryString(e){return/^([10])+$/.test(e)?[!0,[]]:[!1,[c.invalidBinaryStringErrorMessage]]}static isNumeric(e){return/^(\d+)$/.test(e)}static isHexadecatet(e){return/^[0-9A-Fa-f]{4}$/.test(e)}}t.Validator=c,c.IPV4_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/),c.IPV6_PATTERN=new RegExp(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/),c.IPV4_RANGE_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/)([1-9]|[1-2][0-9]|3[0-2])$/),c.IPV6_RANGE_PATTERN=new RegExp(/^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/),c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,32}(0){0,32}$/),c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,128}(0){0,128}$/),c.EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(8)}`),c.SIXTEEN_BIT_SIZE=BigInt(`0b${"1".repeat(16)}`),c.THIRTY_TWO_BIT_SIZE=BigInt(`0b${"1".repeat(32)}`),c.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(128)}`),c.IPV4_SIZE=BigInt("4294967296"),c.IPV6_SIZE=BigInt("340282366920938463463374607431768211456"),c.invalidAsnRangeMessage="ASN number given less than zero or is greater than 32bit",c.invalid16BitAsnRangeMessage="ASN number given less than zero or is greater than 16bit",c.invalidIPv4NumberMessage="IPv4 number given less than zero or is greater than 32bit",c.invalidIPv6NumberMessage="IPv6 number given less than zero or is greater than 128bit",c.invalidOctetRangeMessage="Value given contains an invalid Octet; Value is less than zero or is greater than 8bit",c.invalidHexadecatetMessage="The value given is less than zero or is greater than 16bit",c.invalidOctetCountMessage="An IP4 number cannot have less or greater than 4 octets",c.invalidHexadecatetCountMessage="An IP6 number must have exactly 8 hexadecatet",c.invalidMaskMessage="The Mask is invalid",c.invalidPrefixValueMessage="A Prefix value cannot be less than 0 or greater than 32",c.invalidIPv4CidrNotationMessage="Cidr notation should be in the form [ip number]/[range]",c.InvalidIPCidrRangeMessage="Given IP number portion must is not the start of the range",c.invalidRangeNotationMessage="Range notation should be in the form [first ip]-[last ip]",c.invalidRangeFirstNotGreaterThanLastMessage="First IP in [first ip]-[last ip] must be less than Last IP",c.invalidIPv6CidrNotationString="A Cidr notation string should contain an IPv6 number and prefix",c.takeOutOfRangeSizeMessage="$count is greater than $size, the size of the range",c.cannotSplitSingleRangeErrorMessage="Cannot split an IP range with a single IP number",c.invalidInetNumType="Given ipNumType must be either InetNumType.IPv4 or InetNumType.IPv6",c.invalidBinaryStringErrorMessage="Binary string should contain only contiguous 1s and 0s",c.invalidIPRangeSizeMessage="Given size is zero or greater than maximum size of $iptype",c.invalidIPRangeSizeForCidrMessage="Given size can't be created via cidr prefix",c.invalidIPv4PatternMessage="Given IPv4 is not confirm to a valid IPv6 address",c.invalidIPv6PatternMessage="Given IPv6 is not confirm to a valid IPv6 address"},675:(e,t,r)=>{var s=r(54),i=r(578);function n(e,t,r){var s=e[t]+e[r],i=e[t+1]+e[r+1];s>=4294967296&&i++,e[t]=s,e[t+1]=i}function o(e,t,r,s){var i=e[t]+r;r<0&&(i+=4294967296);var n=e[t+1]+s;i>=4294967296&&n++,e[t]=i,e[t+1]=n}function a(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,a){var c=d[i],l=d[i+1],h=d[a],g=d[a+1];n(u,e,t),o(u,e,c,l);var f=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=f,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=f>>>24^p<<8,u[t+1]=p>>>24^f<<8,n(u,e,t),o(u,e,h,g),f=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=f>>>16^p<<16,u[s+1]=p>>>16^f<<16,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^f<<1,u[t+1]=f>>>31^p<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),h=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),u=new Uint32Array(32),d=new Uint32Array(32);function g(e,t){var r=0;for(r=0;r<16;r++)u[r]=e.h[r],u[r+16]=l[r];for(u[24]=u[24]^e.t,u[25]=u[25]^e.t/4294967296,t&&(u[28]=~u[28],u[29]=~u[29]),r=0;r<32;r++)d[r]=a(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,h[16*r+0],h[16*r+1]),c(2,10,18,26,h[16*r+2],h[16*r+3]),c(4,12,20,28,h[16*r+4],h[16*r+5]),c(6,14,22,30,h[16*r+6],h[16*r+7]),c(0,10,20,30,h[16*r+8],h[16*r+9]),c(2,12,22,24,h[16*r+10],h[16*r+11]),c(4,14,16,26,h[16*r+12],h[16*r+13]),c(6,8,18,28,h[16*r+14],h[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var f=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function p(e,t,r,s){f.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,f[0]=e,t&&(f[1]=t.length),f[2]=1,f[3]=1,r&&f.set(r,32),s&&f.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(f,4*i);t&&(y(this,t),this.c=128)}function y(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,g(e,!1),e.c=0),e.b[e.c++]=t[r]}function m(e){return e<16?"0"+e.toString(16):e.toString(16)}p.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),y(this,e),this},p.prototype.digest=function(e){var t=e&&"binary"!==e&&"hex"!==e?e:new Uint8Array(this.outlen);return s(t instanceof Uint8Array,'out must be "binary", "hex", Uint8Array, or Buffer'),s(t.length>=this.outlen,"out must have at least outlen bytes of space"),function(e,t){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;g(e,!0);for(var r=0;r<e.outlen;r++)t[r]=e.h[r>>2]>>8*(3&r)}(this,t),"hex"===e?function(e){for(var t="",r=0;r<e.length;r++)t+=m(e[r]);return t}(t):t},p.prototype.final=p.prototype.digest,p.ready=function(e){i.ready(function(){e()})};var b=p;e.exports=function(e,t,r,i,n){return!0!==n&&(s(e>=A,"outlen must be at least "+A+", was given "+e),s(e<=I,"outlen must be at most "+I+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=v,"key must be at least "+v+", was given "+t.length),s(t.length<=w,"key must be at most "+w+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===S,"salt must be exactly "+S+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===E,"personal must be exactly "+E+", was given "+i.length))),new b(e,t,r,i)},e.exports.ready=function(e){i.ready(function(){e()})},e.exports.WASM_SUPPORTED=i.SUPPORTED,e.exports.WASM_LOADED=!1;var A=e.exports.BYTES_MIN=16,I=e.exports.BYTES_MAX=64,v=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),w=e.exports.KEYBYTES_MAX=64,S=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),E=e.exports.PERSONALBYTES=16;i.ready(function(t){t||(e.exports.WASM_LOADED=!0,e.exports=i)})},872:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.collapseIPv6Number=t.expandIPv6Number=void 0;const s=r(8),i=r(660);let n=e=>e.includes("/")?`/${e.split("/")[1]}`:"";t.expandIPv6Number=e=>{let t=e=>e.map(e=>s.leftPadWithZeroBit(e,4)).join(":");if(/(:){3,}/.test(e))throw"given IPv6 contains consecutive : more than two";const r=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);if(e.includes("::")){let s=e.split("::"),i=s[0],n=s[1],o=i.split(":").filter(e=>""!==e),a=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(o.length+a.length)),l=t(o);""!==l&&(l+=":");let h=t(a);return""!==h&&(h=":"+h),`${l}${c}${h}${r}`}return`${t(e.split(":"))}${r}`},t.collapseIPv6Number=e=>{const t=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);let r=e.split(":").map(e=>{let t=e.replace(/^0+/,"");return""!==t?t:"0"}).join(":").replace(/((^0)?(:0){2,}|(^0)(:0){1,})/,":");return":"===r.slice(-1)?`${r}:${t}`:(r=r.replace(":0:","::"),`${r}${t}`)}},884:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmNvbnN0IHsgd29ya2VyIH0gPSBhd2FpdCB0c0ltcG9ydCgiLi93b3JrZXIudHMiLCBpbXBvcnQubWV0YS51cmwpOwp3b3JrZXIubGlzdGVuVG9QYXJlbnRQb3J0KCk7Cg=="},896:e=>{e.exports=t(import.meta.url)("fs")},909:()=>{var e;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=s(e);function s(e,t){return function(r,s){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:s}),t&&t(r,s)}}void 0!==t.Reflect&&(r=s(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,s="function"==typeof Symbol,i=s&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",n=s&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,l={create:o?function(){return Q(Object.create(null))}:a?function(){return Q({__proto__:null})}:function(){return Q({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},h=Object.getPrototypeOf(Function),u="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[n]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),s=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var s=this._keys.length,i=r+1;i<s;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[n]=function(){return this.entries()},t.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(N(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return s;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}(),d="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[n]=function(){return this.keys()},e}(),g="function"==typeof WeakMap?WeakMap:function(){var e=l.create(),t=s();return function(){function e(){this._key=s()}return e.prototype.has=function(e){var t=i(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return i(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=s()},e}();function s(){var t;do{t="@@WeakMap@@"+o()}while(l.has(e,t));return e[t]=!0,t}function i(e,s){if(!r.call(e,t)){if(!s)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function n(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function o(){var e=function(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):n(t,e),t}return n(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",r=0;r<16;++r){var s=e[r];4!==r&&6!==r&&8!==r||(t+="-"),s<16&&(t+="0"),t+=s.toString(16).toLowerCase()}return t}}(),f=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),C(e)&&(e=function(){var e,r,s,i;C(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=function(e){var t=e.defineMetadata,r=e.hasOwnMetadata,s=e.getOwnMetadata,i=e.getOwnMetadataKeys,n=e.deleteMetadata,o=new g,a={isProviderFor:function(e,t){var r=o.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new d,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return a}(t.Reflect));var n=new g,o={registerProvider:a,getProvider:l,setProvider:p};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case C(r):r=t;break;case r===t:break;case C(s):s=t;break;case s===t:break;default:void 0===i&&(i=new d),i.add(t)}}function c(t,n){if(!C(r)){if(r.isProviderFor(t,n))return r;if(!C(s)){if(s.isProviderFor(t,n))return r;if(!C(i))for(var o=M(i);;){var a=L(o);if(!a)return;var c=P(a);if(c.isProviderFor(t,n))return H(o),c}}}if(!C(e)&&e.isProviderFor(t,n))return e}function l(e,t){var r,s=n.get(e);return C(s)||(r=s.get(t)),C(r)?(C(r=c(e,t))||(C(s)&&(s=new u,n.set(e,s)),s.set(t,r)),r):r}function h(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function p(e,t,r){if(!h(r))throw new Error("Metadata provider not registered.");var s=l(e,t);if(s!==r){if(!C(s))return!1;var i=n.get(e);C(i)&&(i=new u,n.set(e,i)),i.set(t,r)}return!0}}()),!C(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),y=function(e){var t=new g,r={isProviderFor:function(e,r){var s=t.get(e);return!C(s)&&s.has(r)},OrdinaryDefineOwnMetadata:function(e,t,r,i){s(r,i,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,r){var i=s(t,r,!1);return!C(i)&&_(i.has(e))},OrdinaryGetOwnMetadata:function(e,t,r){var i=s(t,r,!1);if(!C(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var r=[],i=s(e,t,!1);if(C(i))return r;for(var n=M(i.keys()),o=0;;){var a=L(n);if(!a)return r.length=o,r;var c=P(a);try{r[o]=c}catch(e){try{H(n)}finally{throw e}}o++}},OrdinaryDeleteMetadata:function(e,r,i){var n=s(r,i,!1);if(C(n))return!1;if(!n.delete(e))return!1;if(0===n.size){var o=t.get(r);C(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}};return p.registerProvider(r),r;function s(s,i,n){var o=t.get(s),a=!1;if(C(o)){if(!n)return;o=new u,t.set(s,o),a=!0}var c=o.get(i);if(C(c)){if(!n)return;if(c=new u,o.set(i,c),!e.setProvider(s,i,r))throw o.delete(i),a&&t.delete(s),new Error("Wrong provider for target.")}return c}}(p);function m(e,t,r){if(b(e,t,r))return!0;var s=K(t);return!k(s)&&m(e,s,r)}function b(e,t,r){var s=V(t,r,!1);return!C(s)&&_(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(b(e,t,r))return I(e,t,r);var s=K(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=V(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){V(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=K(e);if(null===s)return r;var i=w(s,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var n=new d,o=[],a=0,c=r;a<c.length;a++){var l=c[a];n.has(l)||(n.add(l),o.push(l))}for(var h=0,u=i;h<u.length;h++)l=u[h],n.has(l)||(n.add(l),o.push(l));return o}function S(e,t){var r=V(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function E(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function C(e){return void 0===e}function k(e){return null===e}function x(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(E(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",s=D(e,i);if(void 0!==s){var n=s.call(e,r);if(x(n))throw new TypeError;return n}return function(e,t){if("string"===t){var r=e.toString;if(U(r)&&!x(i=r.call(e)))return i;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i}else{var s;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i;var i,n=e.toString;if(U(n)&&!x(i=n.call(e)))return i}throw new TypeError}(e,"default"===r?"number":r)}function _(e){return!!e}function R(e){var t=B(e,3);return"symbol"==typeof t?t:function(e){return""+e}(t)}function O(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function U(e){return"function"==typeof e}function T(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function D(e,t){var r=e[t];if(null!=r){if(!U(r))throw new TypeError;return r}}function M(e){var t=D(e,n);if(!U(t))throw new TypeError;var r=t.call(e);if(!x(r))throw new TypeError;return r}function P(e){return e.value}function L(e){var t=e.next();return!t.done&&t}function H(e){var t=e.return;t&&t.call(e)}function K(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===h)return t;if(t!==h)return t;var r=e.prototype,s=r&&Object.getPrototypeOf(r);if(null==s||s===Object.prototype)return t;var i=s.constructor;return"function"!=typeof i||i===e?t:i}function V(e,t,r){var s=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function Q(e){return e.__=void 0,delete e.__,e}e("decorate",function(e,t,r,s){if(C(r)){if(!O(e))throw new TypeError;if(!T(t))throw new TypeError;return function(e,t){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t);if(!C(s)&&!k(s)){if(!T(s))throw new TypeError;t=s}}return t}(e,t)}if(!O(e))throw new TypeError;if(!x(t))throw new TypeError;if(!x(s)&&!C(s)&&!k(s))throw new TypeError;return k(s)&&(s=void 0),function(e,t,r,s){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t,r,s);if(!C(n)&&!k(n)){if(!x(n))throw new TypeError;s=n}}return s}(e,t,r=R(r),s)}),e("metadata",function(e,t){return function(r,s){if(!x(r))throw new TypeError;if(!C(s)&&!function(e){switch(E(e)){case 3:case 4:return!0;default:return!1}}(s))throw new TypeError;v(e,t,r,s)}}),e("defineMetadata",function(e,t,r,s){if(!x(r))throw new TypeError;return C(s)||(s=R(s)),v(e,t,r,s)}),e("hasMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),m(e,t,r)}),e("hasOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),b(e,t,r)}),e("getMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),A(e,t,r)}),e("getOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),I(e,t,r)}),e("getMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),w(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),S(e,t)}),e("deleteMetadata",function(e,t,r){if(!x(t))throw new TypeError;if(C(r)||(r=R(r)),!x(t))throw new TypeError;C(r)||(r=R(r));var s=V(t,r,!1);return!C(s)&&s.OrdinaryDeleteMetadata(e,t,r)})}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))},928:e=>{e.exports=t(import.meta.url)("path")},951:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Pool=void 0;const s=r(412),i=r(516);class n{constructor(e){this.backingSet=new o,e.forEach(e=>{this.backingSet.add(e)})}static fromIP(e){let t=e.map(e=>s.RangedSet.fromSingleIP(e));return new n(t)}static fromRangeSet(e){return new n(e)}static fromCidrRanges(e){let t=e.map(e=>e.toRangeSet());return new n(t)}getRanges(){return this.backingSet.asArray()}aggregate(){let e=this.backingSet.asArray().reduce((e,t,r,s)=>{if(0==e.length)return e.push(t),e;{let r=e.pop(),s=r.toCidrRange(),i=t.toCidrRange();if(s.isCidrMergeable(i)){let t=s.merge(i);return e.push(t.toRangeSet()),e}return r.contains(t)?e.push(r):(e.push(r),e.push(t)),e}},[]),t=n.fromRangeSet(e);return t.getRanges().length!==this.getRanges().length?t.aggregate():t}getCidrRange(e){if(e.toRangeSize()>this.getSize())throw new Error(`Not enough IP number in the pool for requested prefix: ${e}`);let t,r;e:for(let s of this.getRanges())for(let i=0n;i+e.toRangeSize()<=s.getSize();i+=1n)try{let r=s.takeSubRange(i,e.toRangeSize());t=r.toCidrRange();let n=s.difference(r);this.removeExact(s),this.add(n);break e}catch(e){if(e instanceof RangeError)continue e;r=e}if(t)return t;throw void 0===r?new Error(`No range big enough in the pool for requested prefix: ${e}`):r}getCidrRanges(e){if(e.toRangeSize()>this.getSize())throw new Error("Prefix greater than pool");let t=(e,r,s)=>{try{let i=this.getCidrRange(r);s.push(i);let n=s.reduce((e,t)=>e+t.getSize(),0n);return e.toRangeSize()===n?s:t(e,r,s)}catch(n){let o=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,o,s)}};return t(e,e,[])}getSize(){return this.aggregate().getRanges().reduce((e,t)=>e+t.getSize(),0n)}resetWith(e){this.backingSet.clear(),this.backingSet=this.backingSet.add(e)}removeExact(e){let t=this.backingSet.removeExact(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}removeOverlapping(e){let t=this.backingSet.removeOverlapping(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}add(e){this.backingSet=this.backingSet.add(e)}clear(){this.backingSet.clear()}}t.Pool=n;class o{constructor(e){this.backingArray=e?this.sortArray(e):new Array}sortArray(e){return e.sort((e,t)=>e.isLessThan(t)?-1:e.isGreaterThan(t)?1:0),e}asArray(){return this.backingArray}isEquals(e){return this.backingArray.length===e.asArray().length&&this.backingArray.every((t,r)=>t.getSize()===e.asArray()[r].getSize())}add(e){let t=this.backingArray;return"push"in e?t=t.concat(e):t.push(e),new o(this.sortArray(t))}removeExact(e){let t=this.backingArray.filter(t=>"push"in e?void 0!==e.find(e=>e.isEquals(t)):!e.isEquals(t));return new o(this.sortArray(t))}removeOverlapping(e){let t=this.backingArray.flatMap(t=>{if("push"in e)return e.flatMap(e=>t.contains(e)?t.difference(e):t.inside(e)?new Array:t.isOverlapping(e)?[t.subtract(e)]:[e]);try{return t.difference(e)}catch(e){return t}});return new o(this.sortArray(t))}clear(){this.backingArray=[]}}},984:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hexadectetNotationToBinaryString=t.binaryStringToHexadecimalString=t.colonHexadecimalNotationToBinaryString=t.hexadecimalStringToHexadecatetString=t.hexadecimalStringToBinaryString=t.bigIntToHexadecimalString=void 0;const s=r(872),i=r(8);t.bigIntToHexadecimalString=e=>e.toString(16),t.hexadecimalStringToBinaryString=e=>BigInt(`0x${e}`).toString(2),t.hexadecimalStringToHexadecatetString=e=>{let r=t.hexadecimalStringToBinaryString(e);if(r.length>16)throw new Error("Given decimal in binary contains digits greater than an Hexadecatet");return i.leftPadWithZeroBit(r,16)},t.colonHexadecimalNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(t.hexadecimalStringToHexadecatetString(r)),""),t.binaryStringToHexadecimalString=e=>BigInt(`0b${e}`).toString(16),t.hexadectetNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(i.leftPadWithZeroBit(t.hexadecimalStringToBinaryString(r),16)),"")}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e].call(r.exports,r,r.exports,o),r.exports}o.m=i,o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.b=new URL("./",import.meta.url);var a={};o.r(a),o.d(a,{Any:()=>fm,BaseBlock:()=>Bp,BaseStringBlock:()=>Rp,BitString:()=>By,BmpString:()=>Wy,Boolean:()=>Ey,CharacterString:()=>om,Choice:()=>pm,Constructed:()=>Ay,DATE:()=>lm,DateTime:()=>um,Duration:()=>dm,EndOfContent:()=>vy,Enumerated:()=>Ny,GeneralString:()=>nm,GeneralizedTime:()=>cm,GraphicString:()=>sm,HexBlock:()=>wp,IA5String:()=>rm,Integer:()=>Ty,Null:()=>wy,NumericString:()=>Xy,ObjectIdentifier:()=>Py,OctetString:()=>ky,Primitive:()=>fy,PrintableString:()=>Zy,RawData:()=>mm,RelativeObjectIdentifier:()=>Ky,Repeated:()=>ym,Sequence:()=>Vy,Set:()=>Qy,TIME:()=>gm,TeletexString:()=>em,TimeOfDay:()=>hm,UTCTime:()=>am,UniversalString:()=>Yy,Utf8String:()=>qy,ValueBlock:()=>Ep,VideotexString:()=>tm,ViewWriter:()=>sp,VisibleString:()=>im,compareSchema:()=>bm,fromBER:()=>yy,verifySchema:()=>Am});const c=t(import.meta.url)("node:url");var l,h,u;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(l||(l={}));class d{value;constructor(e){this.value=e}static Less=new d(l.Less);static Greater=new d(l.Greater);static Equal=new d(l.Equal);isLess(){return this.value===l.Less}isGreater(){return this.value===l.Greater}isEqual(){return this.value===l.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}!function(e){e.V0_6_4="0.6.4",e.V0_6_5="0.6.5",e.V0_6_6="0.6.6",e.V0_6_7="0.6.7",e.V0_7_0="0.7.0"}(h||(h={})),function(e){e.W3F_DAVXY="w3f-davxy",e.W3F="w3f",e.JAMDUNA="jamduna",e.JAVAJAM="javajam"}(u||(u={}));const g=u.W3F,f=[h.V0_6_4,h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0],p="undefined"==typeof process?{}:process.env,y=h.V0_6_5;let m=function(e){if(void 0===e)return;const t=e;if(!Object.values(h).includes(t))throw new Error(`Configured environment variable GP_VERSION is unknown: '${e}'. Use one of: ${f}`);return t}(p.GP_VERSION);const b=p.TEST_SUITE??g;class A{static override(e){m=e}static is(...e){return void 0===m?e.includes(y):e.includes(m)}static isSuite(e){return void 0!==b&&e===b}static isGreaterOrEqual(e){const t=f.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${f}`);return A.is(...f.slice(t))}}function I(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function v(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function w(e){throw new Error(`Unexpected value: ${e}`)}function S(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function E(e){const t=e=>e.split("\n").map(e=>` ${e}`).join("\n").trim();if(null===e)return"<null>";if(void 0===e)return"<undefined>";if(Array.isArray(e))return`[${e.map(e=>E(e))}]`;if(e instanceof Map)return E(Array.from(e.entries()));if("number"==typeof e)return`${e} (0x${e.toString(16)})`;if("object"!=typeof e)return`${e}`;if("toString"in e&&Object.prototype.toString!==e.toString&&k.prototype.toString!==e.toString)return`${e}`;const r=e.constructor.name;let s="Object"!==r?`${r} {`:"{";const i=Object.keys(e),n=i.length<3;for(const r of i)"string"==typeof r&&(s+=n?"":"\n ",s+=`${r}: ${t(E(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const C="undefined"==typeof process?e=>{const t=performance.now();return()=>`${e} took ${performance.now()-t}ms`}:e=>{const t=process.hrtime.bigint();return()=>{const r=process.hrtime.bigint()-t,s=Number(r/1000000n).toFixed(2);return`${e} took ${s}ms`}};class k{toString(){return E(this)}}function x(e){return e}function B(e){return e}const _=Symbol("ok");class R{kind;error;enumMapping;constructor(e,t,r){this.kind=e,this.error=t,this.enumMapping=r}toString(){const e=Object.keys(this.enumMapping).find(e=>this.enumMapping[e]===this.kind)??"?";return`${e} (${this.kind}) - ${O(this.error)}`}}const O=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof R?e.toString():`${e.kind} - ${O(e.error)}`:`${e}`;var t};function U(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${O(e.error)}`}const T={ok:e=>(I(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(I(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>T.error(new R(t,r.error,e),r.details)},N=(t(import.meta.url)("node:assert"),Symbol("compare using"));class D{[N](){return this.toString()}raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=G?String.fromCharCode(e+K-G):String.fromCharCode(e+L);let r="0x";for(const s of e)r+=t(s>>>4),r+=t(15&s);return r}(this.raw)}toJSON(){return this.toString()}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&j(this.raw,e.raw)}compare(e){const t=Math.min(this.length,e.length),r=this.raw,s=e.raw;for(let e=0;e<t;e++){if(r[e]<s[e])return d.Less;if(r[e]>s[e])return d.Greater}return this.length<e.length?d.Less:this.length>e.length?d.Greater:d.Equal}static empty(){return new D(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return D.blobFrom(t.encode(e))}static blobFrom(e){return new D(e)}static blobFromParts(e,...t){const r=e instanceof Uint8Array?[e]:e,s=r.reduce((e,t)=>e+t.length,0)+t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(s);let n=0;for(const e of r)i.set(e,n),n+=e.length;for(const e of t)i.set(e,n),n+=e.length;return new D(i)}static blobFromNumbers(e){I(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new D(t)}static parseBlobNoPrefix(e){const t=e.length;if(t%2==1)throw new Error(`Odd number of nibbles. Invalid hex string: ${e}.`);const r=new ArrayBuffer(t/2),s=new Uint8Array(r);for(let r=0;r<t-1;r+=2){const t=e.substring(r,r+2);s[r/2]=P(t)}return new D(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return D.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield D.blobFrom(this.raw.subarray(t,t+e))}}class M extends D{length;constructor(e,t){super(e),I(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new M(e,t)}static fromNumbers(e,t){I(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new M(r,t)}static zero(e){return new M(new Uint8Array(e),e)}static fill(e,t){I((255&t)===t,"Input has to be a byte.");const r=M.zero(e);return r.raw.fill(t,0,e),r}static parseBytesNoPrefix(e,t){if(e.length>2*t)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2}`);const r=D.parseBlobNoPrefix(e);return new M(r.raw,t)}static parseBytes(e,t){if(e.length>2*t+2)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2-1}`);const r=D.parseBlob(e);return new M(r.raw,t)}isEqualTo(e){return I(this.length===e.length,"Comparing incorrectly typed bytes!"),j(this.raw,e.raw)}asOpaque(){return this}}function P(e){return I(2===e.length,"Two-character string expected"),$(e.charCodeAt(0))<<4|$(e.charCodeAt(1))}const L="0".charCodeAt(0),H="9".charCodeAt(0),K="a".charCodeAt(0),V="f".charCodeAt(0),Q="A".charCodeAt(0),F="F".charCodeAt(0),G=10;function $(e){if(e>=L&&e<=H)return e-L;if(e>=K&&e<=V)return e-K+G;if(e>=Q&&e<=F)return e-Q+G;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function j(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const q=(e,t)=>e.compare(t);class z{data;bitLength;static fromBlob(e,t){return new z(e,t)}static fromBytes(e,t){return new z(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new z(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,I(8*e.length>=t,`Not enough bytes in the data array. Need ${8*e.length} has ${t}.`),this.byteLength=Math.ceil(t/8)}get raw(){return this.data.subarray(0,this.byteLength)}sumWith(e){I(e.bitLength===this.bitLength,`Invalid bit length for sumWith: ${e.bitLength} vs ${this.bitLength}`);const t=e.raw;for(let e=0;e<this.byteLength;e++)this.data[e]|=t[e]}setBit(e,t){I(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const r=Math.floor(e/8),s=1<<e%8;t?this.data[r]|=s:this.data[r]&=~s}isSet(e){I(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const t=Math.floor(e/8),r=1<<e%8;return(this.data[t]&r)>0}*indicesOfSetBits(){for(let e=0;e<this.bitLength;e++){const t=e>>3,r=e-(t<<3);1&~(this.data[t]>>r)||(yield e)}}}const W=Symbol("no key");function J(e,t,r="<root>"){const s=typeof e;if("string"===t){if("string"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("number"===t){if("number"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("boolean"===t){if("boolean"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if(Array.isArray(t)){const s=t[0];if("array"===s){const s=t[1];if("function"==typeof s)return s(e,r);if(!Array.isArray(e))throw new Error(`[${r}] Expected array, got ${e}`);const i=e,n=[];for(const[e,t]of i.entries())n[e]=J(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:J(e,t[1],r);if("object"===s)return Y(t[1],e,r);if("string"===s)return Y(t[1],J(e,s,r),r);if("number"===s){const s=t[0];return Y(t[1],J(e,s,r),r)}throw new Error(`[${r}] Invalid parser type: ${s}`)}if("object"!==s)throw new Error(`[${r}] Expected complex type but got ${s}`);if("object"!=typeof t)throw new Error(`[${r}] Unhandled type ${t}`);if(null===e)throw new Error(`[${r}] Unexpected 'null'`);const i={},n=e,o=t;for(const e of Object.keys(n))i[e]=void 0;for(const e of Object.keys(t))if(e in n){const t=n[e];i[e]=J(t,o[e],`${r}.${e}`)}else Array.isArray(o[e])&&"optional"===o[e][0]&&(i[e]=W);const a=function(e,t){const r=Object.keys(e),s=Object.keys(t);r.sort(),s.sort();const i={},n=Math.max(s.length,s.length);for(let e=0;e<n;e++)i[r[e]]=(i[r[e]]||0)+1,i[s[e]]=(i[s[e]]||0)+2;const o=[],a=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&o.push(1===t?[a(e),a(void 0)]:[a(void 0),a(e)]);return o}(i,t);if(a.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${a.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===W&&delete i[e];return i}function Y(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var X;!function(e){function t(e){return["number",e]}function r(e){return["object",e]}e.fromString=function(e){return["string",e]},e.fromNumber=t,e.castNumber=function(){return t(e=>e)},e.fromAny=r,e.optional=function(e){return["optional",e]},e.nullable=function(e){return["optional",e]},e.array=function(e){return["array",e]},e.record=function(e){return r((t,r)=>{if("object"!=typeof t||null===t)throw new Error("Expected object record for parsing");const s={};for(const[i,n]of Object.entries(t))s[i]=J(n,e,`${r}.${i}`);return s})},e.map=function(e,t){return r((r,s)=>{if("object"!=typeof r||null===r)throw new Error("Expected map for parsing");const i=new Map;for(const[n,o]of Object.entries(r))i.set(J(n,e,`${s}.key`),J(o,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=J(r,e,s);return t(i)})}}(X||(X={}));const Z=e=>v(e,ee(e),`input must have one-byte representation, got ${e}`),ee=e=>(255&e)===e,te=e=>v(e,re(e),`input must have two-byte representation, got ${e}`),re=e=>(65535&e)===e,se=e=>v(e,ie(e),`input must have four-byte representation, got ${e}`),ie=e=>(4294967295&e)>>>0===e,ne=e=>{const t=BigInt(e);return v(t,oe(t),`input must have eight-byte representation, got ${e}`)},oe=e=>(18446744073709551615n&e)===e;function ae(...e){let t=0n;for(const r of e)t+=r;const r=!oe(t);return t&=0xffffffffffffffffn,{overflow:r,value:ne(t)}}function ce(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function le(e){return I(4===e.length,"Input must be a Uint8Array of length 4"),e[0]|e[1]<<8|e[2]<<16|e[3]<<24}const he=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class ue{source;offset;context;static fromBytesBlob(e,t){return new ue(e.raw,t)}static fromBlob(e){return new ue(e)}static decodeObject(e,t,r){const s=t instanceof D?ue.fromBytesBlob(t):ue.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof D?ue.fromBytesBlob(t):ue.fromBlob(t);s.attachContext(r);const i=[];for(;s.bytesRead()<s.source.length;)i.push(s.object(e));return s.finish(),i}dataView;constructor(e,t=0,r){this.source=e,this.offset=t,this.context=r,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}clone(){return new ue(this.source,this.offset,this.context)}bytesRead(){return this.offset}remainingBytes(){const e=this.source.subarray(this.offset),t=e.length;return this.offset+=t,M.fromBlob(e,t)}i8(){return this.getNum(1,()=>this.dataView.getInt8(this.offset))}u8(){return this.getNum(1,()=>this.dataView.getUint8(this.offset))}i16(){return this.getNum(2,()=>this.dataView.getInt16(this.offset,!0))}u16(){return this.getNum(2,()=>this.dataView.getUint16(this.offset,!0))}i24(){const e=this.u24();return e>=2**23?e-2**24:e}u24(){return this.getNum(3,()=>{let e=this.dataView.getUint8(this.offset);return e|=this.dataView.getUint16(this.offset+1,!0)<<8,e})}i32(){return this.getNum(4,()=>this.dataView.getInt32(this.offset,!0))}u32(){return this.getNum(4,()=>this.dataView.getUint32(this.offset,!0))}i64(){return this.getNum(8,()=>this.dataView.getBigInt64(this.offset,!0))}u64(){return this.getNum(8,()=>this.dataView.getBigUint64(this.offset,!0))}bool(){const e=this.u8();if(0===e)return!1;if(1===e)return!0;throw new Error(`Unexpected number when decoding a boolean: ${e}`)}varU32(){this.ensureHasBytes(1);const e=this.source[this.offset],t=ge(e);if(this.offset+=1,0===t)return e;if(t>4)throw new Error(`Unexpectedly large value for u32. l=${t}`);this.ensureHasBytes(t);const r=e+2**(8-t)-256<<8*t;if(1===t)return r+this.u8();if(2===t)return r+this.u16();if(3===t)return r+this.u24();if(0===r)return this.u32();throw new Error(`Unexpectedly large value for u32. l=${t}, mostSignificantByte=${r}`)}varU64(){this.ensureHasBytes(1);const e=this.source[this.offset],t=ge(e);if(this.offset+=1,0===t)return ne(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return ne(this.dataView.getBigUint64(this.offset-t,!0));let r=BigInt(e+2**(8-t)-256)<<BigInt(8*t);for(let e=0;e<t;e+=1)r|=BigInt(this.source[this.offset-t+e])<<BigInt(8*e);return ne(r)}bytes(e){if(0===e)return M.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,M.fromBlob(t,e)}bytesBlob(){const e=this.varU32();this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,D.blobFrom(t)}bitVecFixLen(e){if(0===e)return z.empty(0);const t=Math.ceil(e/8),r=this.bytes(t),s=e%8;if(s>0&&r.raw[t-1]>>s>0)throw new Error("Non-zero bits found in the last byte of bitvec encoding.");return z.fromBytes(r,e)}bitVecVarLen(){const e=this.varU32();return this.bitVecFixLen(e)}object(e){return e.decode(this)}optional(e){return this.bool()?e.decode(this):null}sequenceFixLen(e,t){const r=Array(t);for(let s=0;s<t;s+=1)r[s]=e.decode(this);return r}sequenceVarLen(e){const t=this.varU32();return this.sequenceFixLen(e,t)}resetTo(e){this.offset<e?this.skip(e-this.offset):(I(e>=0,"The offset has to be positive"),this.offset=e)}skip(e){this.ensureHasBytes(e),this.offset+=e}finish(){if(this.offset<this.source.length)throw new Error(`Expecting end of input, yet there are still ${this.source.length-this.offset} bytes left.`)}getNum(e,t){this.ensureHasBytes(e);const r=t();return this.offset+=e,r}ensureHasBytes(e){if(I(e>=0,"Negative number of bytes given."),this.offset+e>this.source.length)throw new Error(`Attempting to decode more data than there is left. Need ${e}, left: ${this.source.length-this.offset}.`)}}const de=[255,254,252,248,240,224,192,128];function ge(e){I(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<de.length;t++)if(e>=de[t])return 8-t;return 0}function fe(e){return I(e.isExact,"The value is not exact size estimation!"),e.bytes}function pe(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const ye=10485760;class me{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new me(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(ye,t),{maxByteLength:ye}),s=new Uint8Array(r);return new me(s,r)}static encodeObject(e,t,r){const s=me.create({expectedLength:e.sizeHint.bytes||512});return s.attachContext(r),s.object(e,t),s.viewResult()}offset=0;context;dataView;constructor(e,t){this.destination=e,this.buffer=t,this.dataView=void 0!==t?new DataView(t):new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}viewResult(){return D.blobFrom(this.destination.subarray(0,this.offset))}i32(e){this.prepareIntegerN(e,4),this.dataView.setInt32(this.offset,e,!0),this.offset+=4}i64(e){const t=2n**64n;I(e<t,"Only for numbers up to 2**64 - 1"),I(-e<=t/2n,"Only for numbers down to -2**63"),this.ensureBigEnough(8),this.dataView.setBigInt64(this.offset,e,!0),this.offset+=8}i24(e){this.prepareIntegerN(e,3),this.dataView.setInt8(this.offset,255&e),this.dataView.setInt16(this.offset+1,e>>8,!0),this.offset+=3}i16(e){this.prepareIntegerN(e,2),this.dataView.setInt16(this.offset,e,!0),this.offset+=2}i8(e){this.prepareIntegerN(e,1),this.dataView.setInt8(this.offset,e),this.offset+=1}bool(e){this.varU32(se(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);I(e<r,`Only for numbers up to 2**${8*t} - 1`),I(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){I(e>=0,"Only for natural numbers."),I(e<2**32,"Only for numbers up to 2**32"),this.varU64(BigInt(e))}varU64(e){const t=BigInt(e);if(0n===t)return this.ensureBigEnough(1),this.destination[this.offset]=0,void(this.offset+=1);let r=2n**56n;if(t>=r)return this.ensureBigEnough(9),this.destination[this.offset]=255,this.dataView.setBigUint64(this.offset+1,t,!0),void(this.offset+=9);let s=r>>7n;for(let e=7;e>=0;e-=1){if(t>=s){this.ensureBigEnough(e+1);const r=2n**BigInt(8*e),s=BigInt(256-2**(8-e))+t/r;this.destination[this.offset]=255&Number(s),this.offset+=1;let i=t%r;for(let t=this.offset;t<this.offset+e;t+=1)this.destination[t]=Number(0xffn&i),i>>=8n;return void(this.offset+=e)}r=s,s>>=7n}throw new Error(`Unhandled number encoding: ${t}`)}bytesBlob(e){this.blob(e.raw)}blob(e){this.varU32(se(e.length)),this.ensureBigEnough(e.length),this.destination.set(e,this.offset),this.offset+=e.length}bytes(e){this.ensureBigEnough(e.length),this.destination.set(e.raw,this.offset),this.offset+=e.length}bitVecFixLen(e){const t=e.raw;this.bytes(M.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(se(t)),this.bitVecFixLen(e)}object(e,t){this.applySizeHint(e),e.encode(this,t)}optional(e,t){const r=null!=t;this.bool(r),r&&(this.applySizeHint(e),e.encode(this,t))}sequenceFixLen(e,t){this.applySizeHint(e,t.length);for(const r of t)e.encode(this,r)}sequenceVarLen(e,t){I(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(se(t.length)),this.sequenceFixLen(e,t)}applySizeHint(e,t=1){const r=e.sizeHint.bytes;r>0&&t>0&&this.ensureBigEnough(r*t,{silent:!0})}ensureBigEnough(e,t={silent:!1}){I(e>=0,"Negative length given");const r=this.offset+e;if(r>ye){if(t.silent)return;throw new Error("The encoded size would reach the maximum of 10485760.")}if(r>this.destination.length){if(void 0!==this.buffer){const e=Math.max(r,this.buffer.byteLength<<1);this.buffer.resize(Math.min(ye,e))}if(r>this.destination.length){if(t.silent)return;throw new Error(`Not enough space in the destination array. Needs ${r}, has ${this.destination.length}.`)}}}}class be{decoder;constructor(e){this.decoder=e}u64=()=>this.decoder.skip(8);u32=()=>this.decoder.skip(4);u24=()=>this.decoder.skip(3);u16=()=>this.decoder.skip(2);u8=()=>this.decoder.skip(1);bool=()=>this.decoder.skip(1);varU32=()=>this.varU64();varU64(){const e=ge(this.decoder.u8());this.decoder.skip(e)}bytes(e){this.decoder.skip(e)}bytesBlob(){const e=this.decoder.varU32();this.decoder.skip(e)}bitVecFixLen(e){this.decoder.skip(Math.ceil(e/8))}bitVecVarLen(){const e=this.decoder.varU32();this.bitVecFixLen(e)}object(e){e.skip(this)}optional(e){this.decoder.bool()&&e.skip(this)}sequenceFixLen(e,t){for(let r=0;r<t;r+=1)e.skip(this)}sequenceVarLen(e){const t=this.decoder.varU32();return this.sequenceFixLen(e,t)}}function Ae(e,t,r){if(t<e.minLength)throw new Error(`${r}: length is below minimal. ${t} < ${e.minLength}`);if(t>e.maxLength)throw new Error(`${r}: length is above maximal. ${t} > ${e.maxLength}`)}class Ie{getView;getValue;getEncoded;cachedValue;cachedView;cachedBlob;constructor(e,t,r){this.getView=e,this.getValue=t,this.getEncoded=r}materialize(){return void 0===this.cachedValue&&(this.cachedValue=this.getValue()),this.cachedValue}view(){return void 0===this.cachedView&&(this.cachedView=this.getView()),this.cachedView}encoded(){return void 0===this.cachedBlob&&(this.cachedBlob=this.getEncoded()),this.cachedBlob}}class ve{decoder;materializedConstructor;descriptors;descriptorsKeys;cache=new Map;initialDecoderOffset;lastDecodedFieldIdx=-1;constructor(e,t,r){this.decoder=e,this.materializedConstructor=t,this.descriptors=r,this.descriptorsKeys=Object.keys(r),this.initialDecoderOffset=e.bytesRead()}materialize(){const e=this.descriptorsKeys,t=Object.fromEntries(e.map(e=>[e,this.get(e).materialize()]));return this.materializedConstructor.create(t)}encoded(){const e=this.descriptorsKeys;if(0===e.length)return D.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return D.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead()))}get(e){const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}decodeUpTo(e){const t=this.descriptorsKeys.indexOf(e),r=this.descriptorsKeys[this.lastDecodedFieldIdx];I(this.lastDecodedFieldIdx<t,`Unjustified call to 'decodeUpTo' -\n the index ($Blobindex}, ${String(e)})\n is already decoded (${this.lastDecodedFieldIdx}, ${String(r)}).\n `);let s=this.cache.get(r);const i=new be(this.decoder);for(let e=this.lastDecodedFieldIdx+1;e<=t;e++){const t=i.decoder.clone(),r=this.descriptorsKeys[e],n=this.descriptors[r];s=new Ie(()=>n.View.decode(t.clone()),()=>n.decode(t.clone()),()=>n.skipEncoded(t.clone())),n.skip(i),this.cache.set(r,s),this.lastDecodedFieldIdx=e}return v(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class we{decoder;descriptor;length;cache=new Map;initialDecoderOffset;lastDecodedIdx=-1;constructor(e,t,r){this.decoder=e,this.descriptor=t,this.initialDecoderOffset=this.decoder.bytesRead(),this.length=r??e.varU32()}*[Symbol.iterator](){for(let e=0;e<this.length;e++){const t=this.get(e),r=v(t,void 0!==t,"We are within 0..this.length so all items are defined.");yield r}}map(e){const t=new Array(this.length);let r=0;for(const s of this)t[r]=e(s),r++;return t}get(e){if(e>=this.length)return;const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}encoded(){return 0===this.length?D.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),D.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){I(this.lastDecodedIdx<e,`Unjustified call to 'decodeUpTo' - the index (${e}) is already decoded (${this.lastDecodedIdx}).`);let t=this.cache.get(this.lastDecodedIdx);const r=new be(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new Ie(()=>i.View.decode(e.clone()),()=>i.decode(e.clone()),()=>i.skipEncoded(e.clone())),i.skip(r),this.cache.set(s,t),this.lastDecodedIdx=s}return v(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Se{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Se(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Se(e,t,r,s,i,null)}constructor(e,t,r,s,i,n){this.name=e,this.sizeHint=t,this.encode=r,this.decode=s,this.skip=i,this.View=n??this}skipEncoded(e){const t=e.bytesRead();this.skip(new be(e));const r=e.bytesRead();return D.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Se(this.name,this.sizeHint,(t,r)=>this.encode(t,e(r)),e=>t(this.decode(e)),this.skip,this.View)}asOpaque(){return this.convert(e=>e,e=>e)}}function Ee(e){return e.convert(e=>(I(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function Ce(e){return{bytes:e,isExact:!0}}var ke,xe;function Be(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function _e(e){return e.View!==e}(xe=ke||(ke={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Se.new(`Bytes<${t}>`,Ce(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),xe.varU32=Se.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),xe.varU64=Se.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),xe.u64=Se.withView("u64",Ce(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),xe.bytes(8)),xe.u32=Se.withView("u32",Ce(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),xe.bytes(4)),xe.u24=Se.withView("u24",Ce(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),xe.bytes(3)),xe.u16=Se.withView("u16",Ce(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),xe.bytes(2)),xe.u8=Se.new("u8",Ce(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),xe.i64=Se.withView("u64",Ce(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),xe.bytes(8)),xe.i32=Se.withView("i32",Ce(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),xe.bytes(4)),xe.i24=Se.withView("i24",Ce(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),xe.bytes(3)),xe.i16=Se.withView("i16",Ce(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),xe.bytes(2)),xe.i8=Se.new("i8",Ce(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),xe.bool=Se.new("bool",Ce(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),xe.blob=Se.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),xe.string=Se.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(D.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),xe.blob),xe.bitVecVarLen=Se.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),xe.bitVecFixLen=e=>Se.new(`BitVec[${e}]`,Ce(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),xe.optional=e=>{const t=Se.new(`Optional<${e.name}>`,pe({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return _e(e)?Se.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,xe.optional(e.View)):t},xe.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Se.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{Ae(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return Ae(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return Ae(t,i,r),s.sequenceFixLen(e,i)},function(e,t){const r={bytes:64*e.sizeHint.bytes,isExact:!1},s=e.name!==e.View.name?`, ${e.View.name}`:"",i=`SeqView<${e.name}${s}>[?]`,n=r=>{const s=r.decoder.varU32();return Ae(t,s,i),r.sequenceFixLen(e,s)};return Se.new(i,r,(e,r)=>{Ae(t,r.length,i);const s=r.encoded();e.bytes(M.fromBlob(s.raw,s.length))},t=>{const r=new we(t.clone(),e);return n(new be(t)),r},n)}(e,t))},xe.sequenceFixLen=(e,t)=>Se.withView(`Sequence<${e.name}>[${t}]`,{bytes:t*e.sizeHint.bytes,isExact:e.sizeHint.isExact},(t,r)=>t.sequenceFixLen(e,r),r=>r.sequenceFixLen(e,t),r=>r.sequenceFixLen(e,t),function(e,{fixedLength:t}){const r={bytes:e.sizeHint.bytes*t,isExact:e.sizeHint.isExact},s=r=>r.sequenceFixLen(e,t),i=e.name!==e.View.name?`, ${e.View.name}`:"",n=`SeqView<${e.name}${i}>[${t}]`;return Se.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(M.fromBlob(r.raw,r.length))},r=>{const i=new we(r.clone(),e,t);return s(new be(r)),i},s)}(e,{fixedLength:t})),xe.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Se.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*pe(e.sizeHint,t.sizeHint).bytes:32*(pe(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const o=Array.from(n.entries());o.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(se(o.length));for(const[r,s]of o)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,o=s??i.varU32();let a=null;for(let s=0;s<o;s+=1){const s=e.decode(i),o=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==a&&r(a,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${s}"!`);n.set(s,o),a=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return _e(t)?Se.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,xe.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},xe.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Se.new(e,t,r,s,i),xe.select=({name:e,sizeHint:t},r)=>Se.withView(e,t,(e,t)=>r(e.getContext()).encode(e,t),e=>r(e.getContext()).decode(e),e=>r(e.decoder.getContext()).skip(e),r(null).View),xe.object=(e,t="object",r=e=>e)=>xe.Class({name:t,create:r},e),xe.Class=(e,t)=>{let r=Ce(0);Be(t,(e,t)=>{r=pe(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Be(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends ve{constructor(r){super(r,e,t)}}return Be(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Se.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(M.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new be(e)),t},s)}(e,t,r,s);return Se.withView(e.name,r,(e,r)=>{Be(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Be(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Re=o(405);const Oe=32,Ue=144,Te=144,Ne=32,De=31;class Me extends k{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Pe extends Me{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Le{emptyHash(){return M.zero(Ne)}}const He=new Le;var Ke,Ve=o(675),Qe=o.n(Ve);function Fe(e,t=He){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Qe()(Ne);for(const t of e)s?.update(t instanceof D?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function Ge(e,t=He){const r=Qe()(Ne),s=e instanceof D?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function $e(e,t=He){return Ge(D.blobFromString(e),t)}function je(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class qe{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return je(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const ze="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,We=null!==(Ke=ze.Buffer)&&void 0!==Ke?Ke:null,Je=ze.TextEncoder?new ze.TextEncoder:null;function Ye(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const Xe="a".charCodeAt(0)-10,Ze="0".charCodeAt(0);function et(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+Xe:r+Ze,r=15&t[i],e[s++]=r>9?r+Xe:r+Ze}return String.fromCharCode.apply(null,e)}const tt=null!==We?e=>{if("string"==typeof e){const t=We.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(We.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")}:e=>{if("string"==typeof e)return Je.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},rt=new Uint8Array(256);for(let e=0;e<64;e++)rt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function st(e){const t=function(e){let t=Math.floor(.75*e.length);const r=e.length;return"="===e[r-1]&&(t-=1,"="===e[r-2]&&(t-=1)),t}(e),r=e.length,s=new Uint8Array(t);let i=0;for(let t=0;t<r;t+=4){const r=rt[e.charCodeAt(t)],n=rt[e.charCodeAt(t+1)],o=rt[e.charCodeAt(t+2)],a=rt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|o>>2,i+=1,s[i]=(3&o)<<6|63&a,i+=1}return s}const it=16384,nt=new qe,ot=new Map;function at(e,t){return je(this,void 0,void 0,function*(){let r=null,s=null,i=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const n=()=>new DataView(r.exports.memory.buffer).getUint32(r.exports.STATE_SIZE,!0),o=nt.dispatch(()=>je(this,void 0,void 0,function*(){if(!ot.has(e.name)){const t=st(e.data),r=WebAssembly.compile(t);ot.set(e.name,r)}const t=yield ot.get(e.name);r=yield WebAssembly.instantiate(t,{})})),a=(e=null)=>{i=!0,r.exports.Hash_Init(e)},c=e=>{if(!i)throw new Error("update() called before init()");(e=>{let t=0;for(;t<e.length;){const i=e.subarray(t,t+it);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(tt(e))},l=new Uint8Array(2*t),h=(e,n=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,r.exports.Hash_Final(n),"binary"===e?s.slice(0,t):et(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<it;let d=u;switch(e.name){case"argon2":case"scrypt":d=()=>!0;break;case"blake2b":case"blake2s":d=(e,t)=>t<=512&&u(e);break;case"blake3":d=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":d=()=>!1}return yield(()=>je(this,void 0,void 0,function*(){r||(yield o);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,it)}))(),{getMemory:()=>s,writeMemory:(e,t=0)=>{s.set(e,t)},getExports:()=>r.exports,setMemorySize:e=>{r.exports.Hash_SetMemorySize(e);const t=r.exports.Hash_GetBuffer(),i=r.exports.memory.buffer;s=new Uint8Array(i,t,e)},init:a,update:c,digest:h,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),o=r.exports.memory.buffer,a=new Uint8Array(o,t,s),c=new Uint8Array(4+s);return function(e,t){const r=t.length>>1;for(let s=0;s<r;s++){const r=s<<1;e[s]=Ye(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(a,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),o=n(),a=4+o,c=r.exports.memory.buffer;if(t.length!==a)throw new Error(`Bad state length (expected ${a} bytes, got ${t.length})`);if(!function(e,t){if(e.length!==2*t.length)return!1;for(let r=0;r<t.length;r++){const s=r<<1;if(t[r]!==Ye(e.charCodeAt(s),e.charCodeAt(s+1)))return!1}return!0}(e.hash,t.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const l=t.subarray(4);new Uint8Array(c,s,o).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!d(e,i))return a(i),c(e),h("hex",n);const o=tt(e);return s.set(o),r.exports.Hash_Calculate(o.length,i,n),et(l,s,t)},hashLength:t}})}new qe,new qe,new DataView(new ArrayBuffer(4)),new qe,new qe,new qe,new qe,new Uint8Array(8),new qe,new qe,new qe;var ct={name:"sha3",data:"AGFzbQEAAAABFARgAAF/YAF/AGACf38AYAN/f38AAwgHAAEBAgEAAwUEAQECAgYOAn8BQZCNBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwABA1IYXNoX0dldFN0YXRlAAUOSGFzaF9DYWxjdWxhdGUABgpTVEFURV9TSVpFAwEKpBwHBQBBgAoL1wMAQQBCADcDgI0BQQBCADcD+IwBQQBCADcD8IwBQQBCADcD6IwBQQBCADcD4IwBQQBCADcD2IwBQQBCADcD0IwBQQBCADcDyIwBQQBCADcDwIwBQQBCADcDuIwBQQBCADcDsIwBQQBCADcDqIwBQQBCADcDoIwBQQBCADcDmIwBQQBCADcDkIwBQQBCADcDiIwBQQBCADcDgIwBQQBCADcD+IsBQQBCADcD8IsBQQBCADcD6IsBQQBCADcD4IsBQQBCADcD2IsBQQBCADcD0IsBQQBCADcDyIsBQQBCADcDwIsBQQBCADcDuIsBQQBCADcDsIsBQQBCADcDqIsBQQBCADcDoIsBQQBCADcDmIsBQQBCADcDkIsBQQBCADcDiIsBQQBCADcDgIsBQQBCADcD+IoBQQBCADcD8IoBQQBCADcD6IoBQQBCADcD4IoBQQBCADcD2IoBQQBCADcD0IoBQQBCADcDyIoBQQBCADcDwIoBQQBCADcDuIoBQQBCADcDsIoBQQBCADcDqIoBQQBCADcDoIoBQQBCADcDmIoBQQBCADcDkIoBQQBCADcDiIoBQQBCADcDgIoBQQBBwAwgAEEBdGtBA3Y2AoyNAUEAQQA2AoiNAQuMAwEIfwJAQQAoAoiNASIBQQBIDQBBACABIABqQQAoAoyNASICcDYCiI0BAkACQCABDQBBgAohAwwBCwJAIAIgAWsiBCAAIAQgAEkbIgNFDQAgA0EDcSEFQQAhBgJAIANBBEkNACABQYCKAWohByADQXxxIQhBACEGA0AgByAGaiIDQcgBaiAGQYAKai0AADoAACADQckBaiAGQYEKai0AADoAACADQcoBaiAGQYIKai0AADoAACADQcsBaiAGQYMKai0AADoAACAIIAZBBGoiBkcNAAsLIAVFDQAgAUHIiwFqIQMDQCADIAZqIAZBgApqLQAAOgAAIAZBAWohBiAFQX9qIgUNAAsLIAAgBEkNAUHIiwEgAhADIAAgBGshACAEQYAKaiEDCwJAIAAgAkkNAANAIAMgAhADIAMgAmohAyAAIAJrIgAgAk8NAAsLIABFDQBBACECQcgBIQYDQCAGQYCKAWogAyAGakG4fmotAAA6AAAgBkEBaiEGIAAgAkEBaiICQf8BcUsNAAsLC+ALAS1+IAApA0AhAkEAKQPAigEhAyAAKQM4IQRBACkDuIoBIQUgACkDMCEGQQApA7CKASEHIAApAyghCEEAKQOoigEhCSAAKQMgIQpBACkDoIoBIQsgACkDGCEMQQApA5iKASENIAApAxAhDkEAKQOQigEhDyAAKQMIIRBBACkDiIoBIREgACkDACESQQApA4CKASETQQApA8iKASEUAkACQCABQcgASw0AQQApA+iKASEVQQApA/iKASEWQQApA/CKASEXQQApA4CLASEYQQApA9CKASEZQQApA+CKASEaQQApA9iKASEbDAELQQApA+CKASAAKQNghSEaQQApA9iKASAAKQNYhSEbQQApA9CKASAAKQNQhSEZIBQgACkDSIUhFEEAKQPoigEhFUEAKQP4igEhFkEAKQPwigEhF0EAKQOAiwEhGCABQekASQ0AIBggACkDgAGFIRggFiAAKQN4hSEWIBcgACkDcIUhFyAVIAApA2iFIRUgAUGJAUkNAEEAQQApA4iLASAAKQOIAYU3A4iLAQsgAyAChSEcIAUgBIUhHSAHIAaFIQcgCSAIhSEIIAsgCoUhHiANIAyFIQkgDyAOhSEKIBEgEIUhCyATIBKFIQxBACkDuIsBIRBBACkDkIsBIRFBACkDoIsBIRJBACkDsIsBIRNBACkDiIsBIQ1BACkDwIsBIQ5BACkDmIsBIR9BACkDqIsBIQ9BwH4hAANAIB4gByALhSAbhSAYhSAPhUIBiYUgFIUgF4UgH4UgDoUhAiAMIB0gCoUgGoUgDYUgE4VCAYmFIAiFIBmFIBaFIBKFIgMgB4UhICAJIAggDIUgGYUgFoUgEoVCAYmFIByFIBWFIBGFIBCFIgQgDoUhISAcIAogFCAehSAXhSAfhSAOhUIBiYUgHYUgGoUgDYUgE4UiBYVCN4kiIiALIBwgCYUgFYUgEYUgEIVCAYmFIAeFIBuFIBiFIA+FIgYgCoVCPokiI0J/hYMgAyAPhUICiSIkhSEOIBYgAoVCKYkiJSAEIBeFQieJIiZCf4WDICKFIQ8gECAFhUI4iSIQIAYgDYVCD4kiJ0J/hYMgAyAbhUIKiSIohSENIAQgHoVCG4kiKSAoIAggAoVCJIkiKkJ/hYOFIRYgBiAdhUIGiSIrIAMgC4VCAYkiLEJ/hYMgEiAChUISiSIthSEXICsgBCAfhUIIiSIuIBUgBYVCGYkiFUJ/hYOFIRsgBiAThUI9iSIdIAQgFIVCFIkiBCAJIAWFQhyJIghCf4WDhSEUIAggHUJ/hYMgAyAYhUItiSIDhSEcIB0gA0J/hYMgGSAChUIDiSIJhSEdIAQgAyAJQn+Fg4UhByAJIARCf4WDIAiFIQggDCAChSICICFCDokiA0J/hYMgESAFhUIViSIEhSEJIAYgGoVCK4kiBSADIARCf4WDhSEKIAQgBUJ/hYMgIEIsiSIEhSELIABB0AlqKQMAIAUgBEJ/hYOFIAKFIQwgJyAoQn+FgyAqhSIFIRggAyAEIAJCf4WDhSICIR4gKiApQn+FgyAQhSIDIR8gLSAuQn+FgyAVhSIEIRogJiAkICVCf4WDhSIGIRMgFSArQn+FgyAshSIoIRkgIyAmICJCf4WDhSIiIRIgLiAsIC1Cf4WDhSImIRUgJyApIBBCf4WDhSInIREgIyAkQn+FgyAlhSIjIRAgAEEIaiIADQALQQAgDzcDqIsBQQAgBTcDgIsBQQAgGzcD2IoBQQAgBzcDsIoBQQAgCzcDiIoBQQAgDjcDwIsBQQAgAzcDmIsBQQAgFzcD8IoBQQAgFDcDyIoBQQAgAjcDoIoBQQAgBjcDsIsBQQAgDTcDiIsBQQAgBDcD4IoBQQAgHTcDuIoBQQAgCjcDkIoBQQAgIjcDoIsBQQAgFjcD+IoBQQAgKDcD0IoBQQAgCDcDqIoBQQAgDDcDgIoBQQAgIzcDuIsBQQAgJzcDkIsBQQAgJjcD6IoBQQAgHDcDwIoBQQAgCTcDmIoBC/gCAQV/QeQAQQAoAoyNASIBQQF2ayECAkBBACgCiI0BIgNBAEgNACABIQQCQCABIANGDQAgA0HIiwFqIQVBACEDA0AgBSADakEAOgAAIANBAWoiAyABQQAoAoiNASIEa0kNAAsLIARByIsBaiIDIAMtAAAgAHI6AAAgAUHHiwFqIgMgAy0AAEGAAXI6AABByIsBIAEQA0EAQYCAgIB4NgKIjQELAkAgAkEESQ0AIAJBAnYiA0EDcSEFQQAhBAJAIANBf2pBA0kNACADQfz///8DcSEBQQAhA0EAIQQDQCADQYAKaiADQYCKAWooAgA2AgAgA0GECmogA0GEigFqKAIANgIAIANBiApqIANBiIoBaigCADYCACADQYwKaiADQYyKAWooAgA2AgAgA0EQaiEDIAEgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQEgBEECdCEDA0AgA0GACmogA0GAigFqKAIANgIAIANBBGohAyABQXxqIgENAAsLCwYAQYCKAQvRBgEDf0EAQgA3A4CNAUEAQgA3A/iMAUEAQgA3A/CMAUEAQgA3A+iMAUEAQgA3A+CMAUEAQgA3A9iMAUEAQgA3A9CMAUEAQgA3A8iMAUEAQgA3A8CMAUEAQgA3A7iMAUEAQgA3A7CMAUEAQgA3A6iMAUEAQgA3A6CMAUEAQgA3A5iMAUEAQgA3A5CMAUEAQgA3A4iMAUEAQgA3A4CMAUEAQgA3A/iLAUEAQgA3A/CLAUEAQgA3A+iLAUEAQgA3A+CLAUEAQgA3A9iLAUEAQgA3A9CLAUEAQgA3A8iLAUEAQgA3A8CLAUEAQgA3A7iLAUEAQgA3A7CLAUEAQgA3A6iLAUEAQgA3A6CLAUEAQgA3A5iLAUEAQgA3A5CLAUEAQgA3A4iLAUEAQgA3A4CLAUEAQgA3A/iKAUEAQgA3A/CKAUEAQgA3A+iKAUEAQgA3A+CKAUEAQgA3A9iKAUEAQgA3A9CKAUEAQgA3A8iKAUEAQgA3A8CKAUEAQgA3A7iKAUEAQgA3A7CKAUEAQgA3A6iKAUEAQgA3A6CKAUEAQgA3A5iKAUEAQgA3A5CKAUEAQgA3A4iKAUEAQgA3A4CKAUEAQcAMIAFBAXRrQQN2NgKMjQFBAEEANgKIjQEgABACQeQAQQAoAoyNASIAQQF2ayEDAkBBACgCiI0BIgFBAEgNACAAIQQCQCAAIAFGDQAgAUHIiwFqIQVBACEBA0AgBSABakEAOgAAIAFBAWoiASAAQQAoAoiNASIEa0kNAAsLIARByIsBaiIBIAEtAAAgAnI6AAAgAEHHiwFqIgEgAS0AAEGAAXI6AABByIsBIAAQA0EAQYCAgIB4NgKIjQELAkAgA0EESQ0AIANBAnYiAUEDcSEFQQAhBAJAIAFBf2pBA0kNACABQfz///8DcSEAQQAhAUEAIQQDQCABQYAKaiABQYCKAWooAgA2AgAgAUGECmogAUGEigFqKAIANgIAIAFBiApqIAFBiIoBaigCADYCACABQYwKaiABQYyKAWooAgA2AgAgAUEQaiEBIAAgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQAgBEECdCEBA0AgAUGACmogAUGAigFqKAIANgIAIAFBBGohASAAQXxqIgANAAsLCwvYAQEAQYAIC9ABkAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAgoAAAAAAAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgA==",hash:"fb24e536"};function lt(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new qe,new qe,new qe,new qe,new qe,new qe,new qe,new qe,new Uint8Array(8),new qe,new Uint8Array(8),new qe,new Uint8Array(8),new qe,new qe,new qe;class ht{hasher;static async create(){return new ht(await function(e=512){if(lt(e))return Promise.reject(lt(e));const t=e/8;return at(ct,t).then(r=>{r.init(e);const s={init:()=>(r.init(e),s),update:e=>(r.update(e),s),digest:e=>r.digest(e,1),save:()=>r.save(),load:e=>(r.load(e),s),blockSize:200-2*t,digestSize:t};return s})}(256))}constructor(e){this.hasher=e}}function ut(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return M.fromBlob(e.hasher.digest("binary"),Ne)}class dt{map=new Map;constructor(){}static new(){return new dt}static fromEntries(e){const t=new dt;for(const[r,s]of e)t.set(r,s);return t}get size(){return this.map.size}has(e){return this.map.has(e.toString())}get(e){return this.map.get(e.toString())?.[1]}[Symbol.iterator](){return this.map.values()}entries(){return this.map.values()}*keys(){for(const e of this.map.values())yield e[0]}*values(){for(const e of this.map.values())yield e[1]}toSortedArray(e){const t=Array.from(this.map.values());return t.sort((t,r)=>e(t[0],r[0]).value),t.map(e=>e[1])}toJSON(){return Object.fromEntries(this)}set(e,t){this.map.set(e.toString(),[e,t])}delete(e){return this.map.delete(e.toString())}}class gt{map;static viewDictionaryKeys(e){return new gt(e)}static from(e){const t=gt.new();return t.insertAll(e),t}static new(){return new gt}constructor(e=dt.new()){this.map=e}get size(){return this.map.size}has(e){return this.map.has(e)}*intersection(e){const t=this.size<e.size?this:e,r=t===this?e:this;for(const e of t)r.has(e)&&(yield e)}*[Symbol.iterator](){for(const e of this.map)yield e[0]}insert(e){return this.map.set(e,!0)}insertAll(e){for(const t of e)this.map.set(t,!0)}delete(e){return this.map.delete(e)}}function ft(e){return e}class pt extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){I(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new pt(t);for(let s=0;s<t;s++)r[s]=e[s];return Object.seal(r),r}static fill(e,t){const r=[];for(let s=0;s<t;s++)r.push(e(s));return pt.new(r,t)}toString(){return E(Array.from(this))}}class yt{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new yt(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new yt([],e);const s=t.slice();for(let t=1;t<r;t++)if(e(s[t-1],s[t]).isGreater())throw new Error(`Expected sorted array, got: ${s}`);return new yt(s,e)}constructor(e,t){this.array=e,this.comparator=t}insert(e){const t=this.binarySearch(e);this.array.splice(t.idx,0,e)}pop(){return this.array.pop()}findIndex(e){const t=this.binarySearch(e);return t.isEqual?t.idx:-1}findExact(e){const t=this.binarySearch(e);if(t.isEqual)return this.array[t.idx]}removeOne(e){const t=this.binarySearch(e);t.isEqual&&this.array.splice(t.idx,1)}has(e){return this.binarySearch(e).isEqual}get length(){return this.array.length}slice(e,t){return this.array.slice(e,t)}binarySearch(e){const t=this.array,r=this.comparator;let s=0,i=t.length;for(;s<i;){const n=i+s>>1,o=r(t[n],e);if(o.isEqual())return{idx:n,isEqual:!0};o.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){I(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator,s=e.array,i=s.length,n=t.array,o=n.length,a=new Array(i+o);let c=0,l=0,h=0;for(;c<i&&l<o;)r(s[c],n[l]).isLess()?a[h++]=s[c++]:(r(s[c],n[l]).isGreater()||(a[h++]=s[c++]),a[h++]=n[l++]);for(;c<i;)a[h++]=s[c++];for(;l<o;)a[h++]=n[l++];return yt.fromSortedArray(r,a)}*[Symbol.iterator](){for(const e of this.array)yield e}}class mt extends yt{static fromArray(e,t=[]){const r=t.slice();r.sort((t,r)=>e(t,r).value);const s=r.length;for(let i=1;i<s;i++)if(e(r[i-1],r[i]).isEqual())throw new Error(`Expected array without duplicates, got: ${t}`);return new mt(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new mt([],e);const r=t.slice(),s=r.length;for(let t=1;t<s;t++)if(e(r[t-1],r[t]).isGreaterOrEqual())throw new Error(`Expected sorted array without duplicates, got: ${r}`);return new mt(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){I(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return mt.fromSortedArray(r,t.array);if(0===t.length)return mt.fromSortedArray(r,e.array);const s=yt.fromTwoSortedCollections(e,t).array,i=s.length;let n=1;for(let e=1;e<i;e++)r(s[e-1],s[e]).isNotEqual()&&(s[n++]=s[e]);return s.length=n,mt.fromSortedArray(r,s)}}class bt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=M.zero(Ne).asOpaque();return r.raw.set(e.raw.subarray(0,De)),[r,t]});return new bt(dt.fromEntries(t))}truncatedKey=M.zero(Ne).asOpaque();constructor(e){this.dict=e}[N](){return this.dict}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.has(this.truncatedKey)}set(e,t){const r=M.zero(Ne);r.raw.set(e.raw.subarray(0,De)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}class At extends k{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;slotDuration;epochLength;rotationPeriod;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;numberECPiecesPerSegment;preimageExpungePeriod;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=Math.floor(e.validatorsCount/3),this.validatorsSuperMajority=2*Math.floor(e.validatorsCount/3)+1,this.coresCount=e.coresCount,this.slotDuration=e.slotDuration,this.epochLength=e.epochLength,this.rotationPeriod=e.rotationPeriod,this.contestLength=e.contestLength,this.ticketsPerValidator=e.ticketsPerValidator,this.maxTicketsPerExtrinsic=e.maxTicketsPerExtrinsic,this.numberECPiecesPerSegment=e.numberECPiecesPerSegment,this.preimageExpungePeriod=e.preimageExpungePeriod}}const It=new At({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026,preimageExpungePeriod:6}),vt=new At({contestLength:500,coresCount:341,epochLength:600,maxTicketsPerExtrinsic:16,rotationPeriod:10,slotDuration:6,ticketsPerValidator:2,validatorsCount:1023,numberECPiecesPerSegment:6,preimageExpungePeriod:19200});class wt{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new wt(new At(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function St(e){const t=vt,{name:r,sizeHint:s}=e(t),i=new Map;return ke.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof At){const t=i.get(s);if(void 0!==t)return t;const r=e(s);return i.set(s,r),r}if(null===s)return e(t);if(null!==s)throw new Error(`[${r}] Unexpected context type ${typeof s} while encoding/decoding.`);throw new Error(`[${r}] Missing context while encoding/decoding!`)})}const Et=(e,t,r)=>"fixedLength"in t?Ee(ke.sequenceFixLen(e,t.fixedLength)).convert(B,ft):Ee(ke.sequenceVarLen(e,t)).convert(B,ft),Ct=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return ke.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),pt.new(e,t)))},kt=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Se.new(`HashDictionary<${e.name}>[?]`,{bytes:r*e.sizeHint.bytes,isExact:!1},(t,r)=>{const i=Array.from(r.values());i.sort((e,t)=>s(e,t).value),t.varU32(se(i.length));for(const r of i)e.encode(t,r)},r=>{const i=dt.new(),n=r.varU32();let o=null;for(let a=0;a<n;a+=1){const n=e.decode(r),a=t(n);if(i.has(a))throw new Error(`Duplicate item in the dictionary encoding: "${a}"!`);if(null!==o&&s(o,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${n}"!`);i.set(a,n),o=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class xt extends k{attempt;signature;static Codec=ke.Class(xt,{attempt:ke.u8.asOpaque(),signature:ke.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new xt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Bt extends k{id;attempt;static Codec=ke.Class(Bt,{id:ke.bytes(Ne),attempt:ke.u8.asOpaque()});static create({id:e,attempt:t}){return new Bt(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const _t=Et(xt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Rt;!function(e){e.bytesN=e=>X.fromString(t=>M.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>X.fromString(t=>M.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>X.fromString(e=>M.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>X.fromString(e=>M.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=X.fromString(D.parseBlob),e.bytesBlobNoPrefix=X.fromString(D.parseBlobNoPrefix),e.ed25519Signature=X.fromString(e=>M.parseBytes(e,64).asOpaque()),e.ticketAttempt=X.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return Z(e)}),e.uint8Array=X.fromAny(e=>{if(Array.isArray(e))return new Uint8Array(e);if(null===e)return new Uint8Array;throw new Error(`Expected an array, got ${typeof e} instead. [uint8Array]`)}),e.bigUint64Array=X.fromAny(e=>{if(Array.isArray(e))return new BigUint64Array(e.map(e=>BigInt(e)));if(null===e)return new BigUint64Array;throw new Error(`Expected an array, got ${typeof e} instead. [bigUint64Array]`)}),e.bigUint64=X.fromAny(e=>BigInt(e))}(Rt||(Rt={}));const Ot=2n**255n-19n,Ut=2n**252n+27742317777372353535851937790883648493n,Tt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Nt=0x6666666666666666666666666666666666666666666666666666666666666658n,Dt={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Ot,n:Ut,h:8,Gx:Tt,Gy:Nt},Mt=(e="")=>{throw new Error(e)},Pt=e=>"string"==typeof e,Lt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Mt("Uint8Array of valid length expected"):e,Ht=e=>new Uint8Array(e),Kt=(e,t=Ot)=>{let r=e%t;return r>=0n?r:t+r},Vt=e=>e instanceof Qt?e:Mt("Point expected");class Qt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new Qt(e.x,e.y,1n,Kt(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Dt,s=(n=e,o=32,e=Lt(Pt(n)?zt(n):Ht(Lt(n)),o)).slice(),i=e[31];var n,o;s[31]=-129&i;const a=Jt(s);!t||0n<=a&&a<2n**256n||Mt("bad y coord 1"),t||0n<=a&&a<Ot||Mt("bad y coord 2");const c=Kt(a*a),l=Kt(c-1n),h=Kt(r*c+1n);let{isValid:u,value:d}=tr(l,h);u||Mt("bad y coordinate 3");const g=1n==(1n&d),f=!!(128&i);return!t&&0n===d&&f&&Mt("bad y coord 3"),f!==g&&(d=Kt(-d)),new Qt(d,a,1n,Kt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{ex:t,ey:r,ez:s}=this,{ex:i,ey:n,ez:o}=Vt(e),a=Kt(t*o),c=Kt(i*s),l=Kt(r*o),h=Kt(n*s);return a===c&&l===h}is0(){return this.equals(Gt)}negate(){return new Qt(Kt(-this.ex),this.ey,this.ez,Kt(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Dt,i=Kt(e*e),n=Kt(t*t),o=Kt(2n*Kt(r*r)),a=Kt(s*i),c=e+t,l=Kt(Kt(c*c)-i-n),h=a+n,u=h-o,d=a-n,g=Kt(l*u),f=Kt(h*d),p=Kt(l*d),y=Kt(u*h);return new Qt(g,f,y,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:o,ez:a,et:c}=Vt(e),{a:l,d:h}=Dt,u=Kt(t*n),d=Kt(r*o),g=Kt(i*h*c),f=Kt(s*a),p=Kt((t+r)*(n+o)-u-d),y=Kt(f-g),m=Kt(f+g),b=Kt(d-l*u),A=Kt(p*y),I=Kt(m*b),v=Kt(p*b),w=Kt(y*m);return new Qt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Mt("cannot multiply by 0"):Gt;if("bigint"==typeof e&&0n<e&&e<Ut||Mt("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(Ft))return or(e).p;let r=Gt,s=Ft;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?r=r.add(i):t&&(s=s.add(i));return r}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(Dt.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Ut/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(Gt))return{x:0n,y:1n};const s=Xt(r,Ot);return 1n!==Kt(r*s)&&Mt("invalid inverse"),{x:Kt(e*s),y:Kt(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Wt(t);return r[31]|=1n&e?128:0,r}toHex(){return jt(this.toRawBytes())}}Qt.BASE=new Qt(Tt,Nt,1n,Kt(Tt*Nt)),Qt.ZERO=new Qt(0n,1n,1n,0n);const{BASE:Ft,ZERO:Gt}=Qt,$t=(e,t)=>e.toString(16).padStart(t,"0"),jt=e=>Array.from(Lt(e)).map(e=>$t(e,2)).join(""),qt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,zt=e=>{const t="hex invalid";if(!Pt(e))return Mt(t);const r=e.length,s=r/2;if(r%2)return Mt(t);const i=Ht(s);for(let r=0,n=0;r<s;r++,n+=2){const s=qt(e.charCodeAt(n)),o=qt(e.charCodeAt(n+1));if(void 0===s||void 0===o)return Mt(t);i[r]=16*s+o}return i},Wt=e=>zt($t(e,64)).reverse(),Jt=e=>BigInt("0x"+jt(Ht(Lt(e)).reverse())),Yt=(...e)=>{const t=Ht(e.reduce((e,t)=>e+Lt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},Xt=(e,t)=>{(0n===e||t<=0n)&&Mt("no inverse n="+e+" mod="+t);let r=Kt(e,t),s=t,i=0n,n=1n,o=1n,a=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-o*e,l=n-a*e;s=r,r=t,i=o,n=a,o=c,a=l}return 1n===s?Kt(i,t):Mt("no inverse")},Zt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ot;return r},er=19681161376707505956807079304988542015446066515923890162744021073123829784752n,tr=(e,t)=>{const r=Kt(t*t*t),s=(e=>{const t=e*e%Ot*e%Ot,r=Zt(t,2n)*t%Ot,s=Zt(r,1n)*e%Ot,i=Zt(s,5n)*s%Ot,n=Zt(i,10n)*i%Ot,o=Zt(n,20n)*n%Ot,a=Zt(o,40n)*o%Ot,c=Zt(a,80n)*a%Ot,l=Zt(c,80n)*a%Ot,h=Zt(l,10n)*i%Ot;return{pow_p_5_8:Zt(h,2n)*e%Ot,b2:t}})(e*Kt(r*r*t)).pow_p_5_8;let i=Kt(e*r*s);const n=Kt(t*i*i),o=i,a=Kt(i*er),c=n===e,l=n===Kt(-e),h=n===Kt(-e*er);return c&&(i=o),(l||h)&&(i=a),1n==(1n&Kt(i))&&(i=Kt(-i)),{isValid:c||l,value:i}};let rr;const sr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,ir={bytesToHex:jt,hexToBytes:zt,concatBytes:Yt,mod:Kt,invert:Xt,randomBytes:(e=32)=>{const t=sr();return t&&t.getRandomValues||Mt("crypto.getRandomValues must be defined"),t.getRandomValues(Ht(e))},sha512Async:async(...e)=>{const t=sr(),r=t&&t.subtle;r||Mt("etc.sha512Async or crypto.subtle must be defined");const s=Yt(...e);return Ht(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let nr;Object.defineProperties(ir,{sha512Sync:{configurable:!1,get:()=>rr,set(e){rr||(rr=e)}}});const or=e=>{const t=nr||(nr=(()=>{const e=[];let t=Ft,r=t;for(let s=0;s<33;s++){r=t,e.push(r);for(let s=1;s<128;s++)r=r.add(t),e.push(r);t=r.double()}return e})()),r=(e,t)=>{let r=t.negate();return e?r:t};let s=Gt,i=Ft;const n=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const c=128*a;let l=Number(e&n);e>>=o,l>128&&(l-=256,e+=1n);const h=c,u=c+Math.abs(l)-1,d=a%2!=0,g=l<0;0===l?i=i.add(r(d,t[h])):s=s.add(r(g,t[u]))}return{p:s,f:i}};var ar=o(625);const cr=32,lr=64;async function hr(e){if(0===e.length)return Promise.resolve([]);const t=e.reduce((e,{message:t,key:r,signature:s})=>e+r.length+s.length+t.length+1,0),r=new Uint8Array(t);let s=0;for(const{key:t,message:i,signature:n}of e){r.set(t.raw,s),s+=cr,r.set(n.raw,s),s+=lr;const e=i.length;I(e<256,`Message needs to be shorter than 256 bytes. Got: ${e}`),r[s]=e,s+=1,r.set(i.raw,s),s+=e}const i=Array.from((0,ar.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}M.blobFromString("jam_val_key_ed25519"),M.blobFromString("jam_val_key_bandersnatch");class ur extends k{anchor;bitfield;validatorIndex;signature;static Codec=ke.Class(ur,{anchor:ke.bytes(Ne).asOpaque(),bitfield:St(e=>ke.bitVecFixLen(e.coresCount)),validatorIndex:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new ur(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const dr=St(e=>Et(ur.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),gr=e=>X.array((e=>X.object({anchor:Rt.bytes32(),bitfield:X.fromString(t=>{const r=Math.ceil(e.coresCount/8);return z.fromBytes(M.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Rt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>ur.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class fr extends k{workReportHash;wasConsideredValid;key;signature;static Codec=ke.Class(fr,{workReportHash:ke.bytes(Ne).asOpaque(),wasConsideredValid:ke.bool,key:ke.bytes(cr).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new fr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class pr extends k{workReportHash;key;signature;static Codec=ke.Class(pr,{workReportHash:ke.bytes(Ne).asOpaque(),key:ke.bytes(cr).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new pr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class yr extends k{isWorkReportValid;index;signature;static Codec=ke.Class(yr,{isWorkReportValid:ke.bool,index:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new yr(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class mr extends k{workReportHash;votesEpoch;votes;static Codec=ke.Class(mr,{workReportHash:ke.bytes(Ne).asOpaque(),votesEpoch:ke.u32.asOpaque(),votes:St(e=>Ee(ke.sequenceFixLen(yr.Codec,e.validatorsSuperMajority)).convert(B,ft))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new mr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class br extends k{verdicts;culprits;faults;static Codec=ke.Class(br,{verdicts:ke.sequenceVarLen(mr.Codec),culprits:ke.sequenceVarLen(pr.Codec),faults:ke.sequenceVarLen(fr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new br(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Ar=e=>se(e),Ir=e=>te(e),vr=e=>se(e),wr=e=>ne(e),Sr=e=>te(e),Er=e=>se(e);function Cr(e,t){return I(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const kr=e=>St(t=>Et(e,{fixedLength:t.validatorsCount}));function xr(e,t){return I(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Br=e=>St(t=>Et(e,{fixedLength:t.epochLength}));class _r extends k{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=ke.Class(_r,{anchor:ke.bytes(Ne).asOpaque(),stateRoot:ke.bytes(Ne).asOpaque(),beefyRoot:ke.bytes(Ne).asOpaque(),lookupAnchor:ke.bytes(Ne).asOpaque(),lookupAnchorSlot:ke.u32.asOpaque(),prerequisites:ke.sequenceVarLen(ke.bytes(Ne).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new _r(e,t,r,s,i,n)}constructor(e,t,r,s,i,n=[]){super(),this.anchor=e,this.stateRoot=t,this.beefyRoot=r,this.lookupAnchor=s,this.lookupAnchorSlot=i,this.prerequisites=n}}class Rr extends k{treeRoot;index;static Codec=ke.Class(Rr,{treeRoot:ke.bytes(Ne),index:ke.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Rr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Or extends k{hash;len;static Codec=ke.Class(Or,{hash:ke.bytes(Ne).asOpaque(),len:ke.u32});static create({hash:e,len:t}){return new Or(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class Ur extends k{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=ke.Class(Ur,{service:ke.u32.asOpaque(),codeHash:ke.bytes(Ne).asOpaque(),payload:ke.blob,refineGasLimit:ke.u64.asOpaque(),accumulateGasLimit:ke.u64.asOpaque(),importSegments:Et(Rr.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:ke.sequenceVarLen(Or.Codec),exportCount:ke.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:o,exportCount:a}){return new Ur(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=o,this.exportCount=a}}function Tr(e){return v(e,e>=Nr&&e<=Dr,`WorkItemsCount: Expected '${Nr} <= count <= ${Dr}' got ${e}`)}const Nr=1,Dr=16;class Mr extends k{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=ke.Class(Mr,{authorization:ke.blob,authCodeHost:ke.u32.asOpaque(),authCodeHash:ke.bytes(Ne).asOpaque(),parametrization:ke.blob,context:_r.Codec,items:ke.sequenceVarLen(Ur.Codec).convert(e=>e,e=>pt.new(e,Tr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Mr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){super(),this.authorization=e,this.authCodeHost=t,this.authCodeHash=r,this.parametrization=s,this.context=i,this.items=n}}var Pr,Lr;(Lr=Pr||(Pr={}))[Lr.ok=0]="ok",Lr[Lr.outOfGas=1]="outOfGas",Lr[Lr.panic=2]="panic",Lr[Lr.badCode=3]="badCode",Lr[Lr.codeOversize=4]="codeOversize";class Hr extends k{kind;okBlob;static Codec=ke.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(se(t.kind)),t.kind===Pr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Pr.ok){const r=e.bytesBlob();return new Hr(t,r)}if(t>Pr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Hr(t)},e=>{e.decoder.varU32()===Pr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Kr extends k{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=ke.Class(Kr,{gasUsed:ke.varU64.asOpaque(),importedSegments:ke.varU32,extrinsicCount:ke.varU32,extrinsicSize:ke.varU32,exportedSegments:ke.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Kr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.gasUsed=e,this.importedSegments=t,this.extrinsicCount=r,this.extrinsicSize=s,this.exportedSegments=i}}class Vr{serviceId;codeHash;payloadHash;gas;result;load;static Codec=ke.Class(Vr,{serviceId:ke.u32.asOpaque(),codeHash:ke.bytes(Ne).asOpaque(),payloadHash:ke.bytes(Ne),gas:ke.u64.asOpaque(),result:Hr.Codec,load:Kr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new Vr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.serviceId=e,this.codeHash=t,this.payloadHash=r,this.gas=s,this.result=i,this.load=n}}class Qr extends k{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=ke.Class(Qr,{hash:ke.bytes(Ne).asOpaque(),length:ke.u32,erasureRoot:ke.bytes(Ne),exportsRoot:ke.bytes(Ne).asOpaque(),exportsCount:ke.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new Qr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.hash=e,this.length=t,this.erasureRoot=r,this.exportsRoot=s,this.exportsCount=i}}class Fr extends k{workPackageHash;segmentTreeRoot;static Codec=ke.Class(Fr,{workPackageHash:ke.bytes(Ne).asOpaque(),segmentTreeRoot:ke.bytes(Ne).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new Fr(e,t)}}class Gr extends k{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=ke.Class(Gr,{workPackageSpec:Qr.Codec,context:_r.Codec,coreIndex:A.isGreaterOrEqual(h.V0_6_5)?ke.varU32.convert(e=>se(e),e=>{if(!re(e))throw new Error(`Core index exceeds U16: ${e}`);return Sr(e)}):ke.u16.asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),authorizationOutput:ke.blob,segmentRootLookup:Ee(ke.sequenceVarLen(Fr.Codec)),results:ke.sequenceVarLen(Vr.Codec).convert(e=>e,e=>pt.new(e,Tr(e.length))),authorizationGasUsed:ke.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:o,authorizationGasUsed:a}){return new Gr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=o,this.authorizationGasUsed=a}}const $r=[2,3];class jr extends k{validatorIndex;signature;static Codec=ke.Class(jr,{validatorIndex:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({validatorIndex:e,signature:t}){return new jr(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class qr extends k{report;slot;credentials;static Codec=ke.Class(qr,{report:Gr.Codec,slot:ke.u32.asOpaque(),credentials:Et(jr.Codec,{minLength:$r[0],maxLength:$r[1],typicalLength:$r[1]})});static create({report:e,slot:t,credentials:r}){return new qr(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const zr=St(e=>Et(qr.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class Wr extends k{bandersnatch;ed25519;static Codec=ke.Class(Wr,{bandersnatch:ke.bytes(Oe).asOpaque(),ed25519:ke.bytes(cr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new Wr(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class Jr extends k{entropy;ticketsEntropy;validators;static Codec=ke.Class(Jr,{entropy:ke.bytes(Ne).asOpaque(),ticketsEntropy:ke.bytes(Ne).asOpaque(),validators:kr(Wr.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new Jr(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const Yr=e=>{const t=e.encoded().raw,r=t.length-96;return D.blobFrom(t.subarray(0,r))};class Xr extends k{static Codec=ke.Class(Xr,{parentHeaderHash:ke.bytes(Ne).asOpaque(),priorStateRoot:ke.bytes(Ne).asOpaque(),extrinsicHash:ke.bytes(Ne).asOpaque(),timeSlotIndex:ke.u32.asOpaque(),epochMarker:ke.optional(Jr.Codec),ticketsMarker:ke.optional(Br(Bt.Codec)),offendersMarker:ke.sequenceVarLen(ke.bytes(cr).asOpaque()),bandersnatchBlockAuthorIndex:ke.u16.asOpaque(),entropySource:ke.bytes(96).asOpaque(),seal:ke.bytes(96).asOpaque()});static create(e){return Object.assign(Xr.empty(),e)}parentHeaderHash=M.zero(Ne).asOpaque();priorStateRoot=M.zero(Ne).asOpaque();extrinsicHash=M.zero(Ne).asOpaque();timeSlotIndex=Ar(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=Ir(0);entropySource=M.zero(96).asOpaque();seal=M.zero(96).asOpaque();constructor(){super()}static empty(){return new Xr}}class Zr extends Me{static Codec=ke.Class(Zr,{hash:ke.bytes(Ne).asOpaque(),data:Xr.Codec.View});static create({hash:e,data:t}){return new Me(e,t)}}const es=Zr.Codec;class ts extends k{requester;blob;static Codec=ke.Class(ts,{requester:ke.u32.asOpaque(),blob:ke.blob});static create({requester:e,blob:t}){return new ts(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const rs=ke.sequenceVarLen(ts.Codec);class ss extends k{tickets;preimages;guarantees;assurances;disputes;static Codec=ke.Class(ss,{tickets:_t,preimages:rs,guarantees:zr,assurances:dr,disputes:br.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new ss(e,t,i,r,s)}constructor(e,t,r,s,i){super(),this.tickets=e,this.preimages=t,this.guarantees=r,this.assurances=s,this.disputes=i}}class is extends k{header;extrinsic;static Codec=ke.Class(is,{header:Xr.Codec,extrinsic:ss.Codec});static create({header:e,extrinsic:t}){return new is(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ns=X.object({target:Rt.bytes32(),vote:"boolean",key:Rt.bytes32(),signature:Rt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>fr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),os=X.object({target:Rt.bytes32(),key:Rt.bytes32(),signature:Rt.ed25519Signature},({target:e,key:t,signature:r})=>pr.create({workReportHash:e,key:t,signature:r})),as=X.object({vote:"boolean",index:"number",signature:Rt.ed25519Signature},({vote:e,index:t,signature:r})=>yr.create({isWorkReportValid:e,index:t,signature:r})),cs=X.object({target:Rt.bytes32(),age:"number",votes:X.array(as)},({target:e,age:t,votes:r})=>mr.create({workReportHash:e,votesEpoch:t,votes:r})),ls=X.object({verdicts:X.array(cs),culprits:X.array(os),faults:X.array(ns)},({verdicts:e,culprits:t,faults:r})=>br.create({verdicts:e,culprits:t,faults:r})),hs=X.object({anchor:Rt.bytes32(),state_root:Rt.bytes32(),beefy_root:Rt.bytes32(),lookup_anchor:Rt.bytes32(),lookup_anchor_slot:"number",prerequisites:X.array(Rt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>_r.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),us=X.object({ok:X.optional(X.fromString(D.parseBlob)),out_of_gas:X.optional(X.fromAny(()=>null)),panic:X.optional(X.fromAny(()=>null)),bad_code:X.optional(X.fromAny(()=>null)),code_oversize:X.optional(X.fromAny(()=>null))},e=>{const{ok:t,out_of_gas:r,panic:s,bad_code:i,code_oversize:n}=e;if(void 0!==t)return new Hr(se(Pr.ok),t);if(null===r)return new Hr(se(Pr.outOfGas));if(null===s)return new Hr(se(Pr.panic));if(null===i)return new Hr(se(Pr.badCode));if(null===n)return new Hr(se(Pr.codeOversize));throw new Error("Invalid WorkExecResult")}),ds=X.object({gas_used:X.fromNumber(e=>wr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Kr.create({gasUsed:wr(e),importedSegments:se(t),extrinsicCount:se(r),extrinsicSize:se(s),exportedSegments:se(i)})),gs=X.object({service_id:"number",code_hash:Rt.bytes32(),payload_hash:Rt.bytes32(),accumulate_gas:X.fromNumber(e=>wr(e)),result:us,refine_load:ds},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>Vr.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),fs=X.object({hash:Rt.bytes32(),length:"number",erasure_root:Rt.bytes32(),exports_root:Rt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>Qr.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),ps=X.object({work_package_hash:Rt.bytes32(),segment_tree_root:Rt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>Fr.create({workPackageHash:e,segmentTreeRoot:t})),ys=X.object({package_spec:fs,context:hs,core_index:"number",authorizer_hash:Rt.bytes32(),auth_output:X.fromString(D.parseBlob),segment_root_lookup:X.array(ps),results:X.array(gs),auth_gas_used:X.fromNumber(e=>wr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:o,auth_gas_used:a})=>{const c=pt.new(n,Tr(n.length));return Gr.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:o,results:c,authorizationGasUsed:a})}),ms=X.object({validator_index:"number",signature:Rt.ed25519Signature},({validator_index:e,signature:t})=>jr.create({validatorIndex:e,signature:t})),bs=X.object({report:ys,slot:"number",signatures:X.array(ms)},({report:e,slot:t,signatures:r})=>qr.create({report:e,slot:t,credentials:r})),As=X.array(bs),Is=X.object({requester:"number",blob:X.fromString(D.parseBlob)},({requester:e,blob:t})=>ts.create({requester:e,blob:t})),vs=X.array(Is),ws=X.object({attempt:Rt.ticketAttempt,signature:X.fromString(e=>M.parseBytes(e,784).asOpaque())},e=>xt.create({attempt:e.attempt,signature:e.signature})),Ss=X.array(ws),Es=X.fromString(e=>M.parseBytes(e,96).asOpaque()),Cs=X.object({bandersnatch:Rt.bytes32(),ed25519:Rt.bytes32()},Wr.create),ks=X.object({entropy:Rt.bytes32(),tickets_entropy:Rt.bytes32(),validators:X.array(Cs)},e=>Jr.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),xs=X.object({id:Rt.bytes32(),attempt:Rt.ticketAttempt},e=>Bt.create({id:e.id,attempt:e.attempt})),Bs=X.object({parent:Rt.bytes32(),parent_state_root:Rt.bytes32(),extrinsic_hash:Rt.bytes32(),slot:"number",epoch_mark:X.optional(ks),tickets_mark:X.optional(X.array(xs)),offenders_mark:X.array(Rt.bytes32()),author_index:"number",entropy_source:Es,seal:Es},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:o,author_index:a,entropy_source:c,seal:l})=>{const h=Xr.empty();return h.parentHeaderHash=e,h.priorStateRoot=t,h.extrinsicHash=r,h.timeSlotIndex=s,h.epochMarker=i??null,h.ticketsMarker=n??null,h.offendersMarker=o,h.bandersnatchBlockAuthorIndex=a,h.entropySource=c,h.seal=l,h});class _s extends k{name;ip;port;static fromString(e){const[t,r]=e.split("@"),s=r.substring(0,r.lastIndexOf(":")),i=r.substring(r.lastIndexOf(":")+1);if(""===t||""===s||""===i)throw new Error(`Invalid bootnode format, expected: <name>@<ip>:<port>, got: "${e}"`);const n=Number.parseInt(i);if(!re(n))throw new Error(`Invalid port number: "${i}"`);return new _s(t,s,n)}constructor(e,t,r){super(),this.name=e,this.ip=t,this.port=r}}class Rs extends k{bootnodes;id;genesisHeader;genesisState;static fromJson=X.object({bootnodes:X.optional(X.array(X.fromString(_s.fromString))),id:"string",genesis_header:Rt.bytesBlobNoPrefix,genesis_state:X.map(Rt.bytesNNoPrefix(31),Rt.bytesBlobNoPrefix)},e=>Rs.create({bootnodes:e.bootnodes,id:e.id,genesisHeader:e.genesis_header,genesisState:e.genesis_state??new Map}));static create({bootnodes:e=[],id:t="",genesisHeader:r=D.empty(),genesisState:s=new Map}){return new Rs({bootnodes:e,id:t,genesisHeader:r,genesisState:s})}constructor(e){super(),this.bootnodes=e.bootnodes,this.id=e.id,this.genesisHeader=e.genesisHeader,this.genesisState=e.genesisState}}const Os=t(import.meta.url)("node:fs");var Us=o.n(Os);const Ts=t(import.meta.url)("node:os");var Ns=o.n(Ts);const Ds=JSON.parse('{"$schema":"https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":false},"chain_spec":{"id":"typeberry-dev","bootnodes":["eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345","en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346","ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"],"genesis_header":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da293d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e948e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260fafff16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea020000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","genesis_state":{"01000000000000000000000000000000000000000000000000000000000000":"08000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","02000000000000000000000000000000000000000000000000000000000000":"0b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb0","03000000000000000000000000000000000000000000000000000000000000":"00","04000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf426000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000085f9095f4abd040839d793d89ab5ff25c61e50c844ab6765e2c0b22373b5a8f6fbe5fc0cd61fdde580b3d44fe1be127197e33b91960b10d2c6fc75aec03f36e16c2a8204961097dbc2c5ba7655543385399cc9ef08bf2e520ccf3b0a7569d88492e630ae2b14e758ab0960e372172203f4c9a41777dadd529971d7ab9d23ab29fe0e9c85ec450505dde7f5ac038274cf01aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d48e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e33d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d03d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d05e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161df16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d0aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bcaa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e300","05000000000000000000000000000000000000000000000000000000000000":"00000000","06000000000000000000000000000000000000000000000000000000000000":"6f6ad2224d7d58aec6573c623ab110700eaca20a48dc2965d535e466d524af2a835ac82bfa2ce8390bb50680d4b7a73dfa2a4cff6d8c30694b24a605f9574eafd2d34655ebcad804c56d2fd5f932c575b6a5dbb3f5652c5202bcc75ab9c2cc958a715731759b7fceaae288bcb70a605c31cbdfae83d0f4a45dfc2b2458dc9fae","07000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","08000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","09000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0a000000000000000000000000000000000000000000000000000000000000":"0000","0b000000000000000000000000000000000000000000000000000000000000":"00000000","0c000000000000000000000000000000000000000000000000000000000000":"00000000000000000000000000","0d000000000000000000000000000000000000000000000000000000000000":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0e000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","0f000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","ff000000000000000000000000000000000000000000000000000000000000":"15f8485e3a88e86182e63280720d5ec9892578f0e577fb1bcdda5cf49795081500e40b540200000064000000000000006400000000000000100500000000000004000000","00fe00ff00ff00ff6326432b5b3213dfd1609495e13c6b276cb474d6796453":"09626f6f74737472617000000000000000000020000a00000000000628023307320015","00fe00ff00ff00fff8485e3a88e86182e63280720d5ec9892578f0e577fb1b":"09626f6f747374726170000000000000020000200032040000050283ae7900300194012f027802280d00000028ae00000028ab029511e07b10187b15107b1608648664783309043307000001ac967c9566fc5106769587047d7833050159083a8489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac564564587b175010029c026478e45607c95707d88709e48707c98707887720d479098217c8750594983307000001da95072805330801821018821510821608951120320000951150ff7b10a8007b15a0007b169800330908ac98e7003309fcaa97e5015107e101958af8957508510a457d583306015908408489ff003306025329c0002d3306035329e000253306045329f0001d3306055329f800153306065329fc000d8898fe009a860801ae6a092890003306017b166457646864a6501004e501821a51077be4a607c9a70753176072c85a089576a09587607b1751064c7d783305015908378489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac562a016458501006810128073305330701e45608c95808e47808c97808330921ae981d33083307000001018210a8008215a000821698009511b00032008219c89505c857077c792051090933083307286e958adf957521510a547d573306015907378477ff003306025327c0002d3306035327e000253306045327f0001d3306055327f800153306065327fc000d8877fe009a7608017b1aac6a920064576468501008e6006478821a28073306330801c86507e46a09c96909e6890801c878088088fc330964330a640a0964757b1708481114951714330804951908330a040a0395171833098000330850100a4a330820a107330964951a1864570a0b81180833070000023b080000029889183b090300029889103b090200029888083b080100023308202806ff0000003307000001330832008d7a84aa07c8a70b510a0e647c0178c895cc01acbcfbc9a903843cf8c8cb0a580c1d8482ff0014090101010101010101ca920c017bbc95bb08acabfb843907520905280ec8a9090178a895aa01ac9afb320051089b0064797c77510791005127ff0090006c7a570a09330a330828735527c0000d330a01330b80284a5527e0000e330a02330b40ff283c5527f0000e330a03330b20ff282e5527f8000e330a04330b10ff28205527fc000e330a05330b08ff2812887afe00330b04ff93ab02ff85aa0701ae8a2b3308c8b70764ab01c8b90c7ccc97880895bbffd4c808520bf28aa903cf9707c88707320032000000002124492a21494a22212121212132154a9224a5909a248d88482422494924242424244426ad0a258924a524121212121222a3504d92a43022a292a44a52120909090909914585aa26c924a924494a1421a984909090903c54495a92241140962465495111942a24854421514814124544a6342549923a","0023000000000000478648cd19b4f812f897a26976ecf312eac28508b4368d":"0100000000","004b000400000000f324d112c31c3778a072940b55dd35f3a4b77e72d2d2db":"0100000000"}},"database_base_path":"./database"}');class Ms{omitSealVerification;static fromJson=X.object({omit_seal_verification:"boolean"},Ms.new);static new({omit_seal_verification:e}){return new Ms(e)}constructor(e){this.omitSealVerification=e}}const Ps="dev",Ls={name:Ns().hostname(),config:Ps};var Hs;!function(e){e.Tiny="tiny",e.Full="full"}(Hs||(Hs={}));const Ks=X.fromString((e,t)=>{switch(e){case Hs.Tiny:return Hs.Tiny;case Hs.Full:return Hs.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class Vs{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=X.object({$schema:"string",version:"number",flavor:Ks,chain_spec:Rs.fromJson,database_base_path:"string",authorship:Ms.fromJson},Vs.new);static new({$schema:e,version:t,flavor:r,chain_spec:s,database_base_path:i,authorship:n}){if(1!==t)throw new Error("Only version=1 config is supported.");return new Vs(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.$schema=e,this.version=t,this.flavor=r,this.chainSpec=s,this.databaseBasePath=i,this.authorship=n}}var Qs;function Fs(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===Qs[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return Qs[t]}!function(e){e[e.TRACE=1]="TRACE",e[e.LOG=2]="LOG",e[e.INFO=3]="INFO",e[e.WARN=4]="WARN",e[e.ERROR=5]="ERROR"}(Qs||(Qs={}));class Gs{options;static create(e,t){return e===Qs.TRACE?new $s(t):e===Qs.LOG?new js(t):e===Qs.INFO?new qs(t):new Gs(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(Qs.WARN,e,t,r)}error(e,t,r){this.push(Qs.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),o=function(e,t){let r=t;for(;;){const s=e.modules.get(r);if(void 0!==s)return s;const i=r.lastIndexOf("/");if(-1===i)return e.defaultLevel;r=t.substring(0,i)}}(this.options,t),a=Qs[e].padEnd(5);if(e<o)return;const c=`${a} [${n}] ${s}\n\t@ ${i}`;e===Qs.WARN?console.warn(c):e===Qs.ERROR?console.error(c):console.info(c)}}class $s extends Gs{trace(e,t,r){this.push(Qs.TRACE,e,t,r)}log(e,t,r){this.push(Qs.LOG,e,t,r)}info(e,t,r){this.push(Qs.INFO,e,t,r)}}class js extends Gs{trace(e,t,r){}log(e,t,r){this.push(Qs.LOG,e,t,r)}info(e,t,r){this.push(Qs.INFO,e,t,r)}}class qs extends Gs{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(Qs.INFO,e,t,r)}}const zs={workingDir:"",defaultLevel:Qs.LOG,modules:new Map},Ws={options:zs,transport:Gs.create(zs.defaultLevel,zs)};class Js{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new Js(t??r,r,Ws)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=Gs.create(t,e);Ws.options=e,Ws.transport=r}static configureAll(e,t,r){const s=function(e,t,r){const s=new Map,i=e.toLowerCase().split(",");let n=t;for(const e of i){const t=e.trim();if(0!==t.length)if(t.includes("=")){const[e,r]=t.split("=");s.set(e.trim(),Fs(r.trim()))}else n=Fs(t)}const o="".split("/");return o.pop(),o.pop(),{defaultLevel:n,modules:s,workingDir:r??o.join("/")}}(e,t,r);Js.configureAllFromOptions(s)}constructor(e,t,r){this.moduleName=e,this.fileName=t,this.config=r}trace(e){this.config.transport.trace(this.moduleName,this.fileName,e)}log(e){this.config.transport.log(this.moduleName,this.fileName,e)}info(e){this.config.transport.info(this.moduleName,this.fileName,e)}warn(e){this.config.transport.warn(this.moduleName,this.fileName,e)}error(e){this.config.transport.error(this.moduleName,this.fileName,e)}}const Ys=t(import.meta.url)("node:worker_threads"),Xs="best hash and posterior state root";class Zs{chainSpec;root;extrinsics;headers;postStateRoots;constructor(e,t){this.chainSpec=e,this.root=t,this.extrinsics=this.root.subDb("extrinsics"),this.headers=this.root.subDb("headers"),this.postStateRoots=this.root.subDb("postStateRoots")}async setPostStateRoot(e,t){await this.postStateRoots.put(e.raw,t.raw)}getPostStateRoot(e){const t=this.postStateRoots.get(e.raw);return void 0===t?null:M.fromBlob(t,Ne).asOpaque()}async insertBlock(e){const t=e.data.header.view().encoded(),r=e.data.extrinsic.view().encoded();await this.root.db.transaction(()=>{this.headers.put(e.hash.raw,t.raw),this.extrinsics.put(e.hash.raw,r.raw)})}async setBestHeaderHash(e){await this.root.db.put(Xs,e.raw)}getBestHeaderHash(){const e=this.root.db.get(Xs);return void 0===e?M.zero(Ne).asOpaque():M.fromBlob(e,Ne).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:ue.decodeObject(Xr.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:ue.decodeObject(ss.Codec.View,t,this.chainSpec)}}const ei=(ti={open:()=>r.open},ri={},o.d(ri,ti),ri);var ti,ri;class si{db;constructor(e,t=!1){this.db=ei.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}const ii=e=>Se.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=Ge(e.skipEncoded(r));return new Me(s.asOpaque(),e.decode(t))},e.skip,e.View);class ni extends k{workReport;timeout;static Codec=ke.Class(ni,{workReport:ii(Gr.Codec),timeout:ke.u32.asOpaque()});static create({workReport:e,timeout:t}){return new ni(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}class oi extends k{headerHash;mmr;postStateRoot;reported;static Codec=ke.Class(oi,{headerHash:ke.bytes(Ne).asOpaque(),mmr:ke.object({peaks:Ee(ke.sequenceVarLen(ke.optional(ke.bytes(Ne))))}),postStateRoot:ke.bytes(Ne).asOpaque(),reported:kt(Fr.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new oi(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}function ai(e,t){return I(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const ci=e=>St(t=>Et(e,{fixedLength:t.coresCount})),li=()=>Ee(ke.sequenceVarLen(ke.bytes(Ne))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return mt.fromSortedArray(di,t)}),hi=li();class ui{goodSet;badSet;wonkySet;punishSet;static Codec=ke.Class(ui,{goodSet:hi,badSet:hi,wonkySet:hi,punishSet:li()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new ui(e,t,r,s)}constructor(e,t,r,s){this.goodSet=e,this.badSet=t,this.wonkySet=r,this.punishSet=s}static fromSortedArrays({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new ui(mt.fromSortedArray(di,e),mt.fromSortedArray(di,t),mt.fromSortedArray(di,r),mt.fromSortedArray(di,s))}}function di(e,t){return e.compare(t)}class gi{service;gasLimit;static Codec=ke.Class(gi,{service:ke.u32.asOpaque(),gasLimit:ke.u64.asOpaque()});static create({service:e,gasLimit:t}){return new gi(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class fi{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=ke.Class(fi,{manager:ke.u32.asOpaque(),authManager:A.isGreaterOrEqual(h.V0_6_7)?ci(ke.u32.asOpaque()):St(e=>ke.u32.asOpaque().convert(e=>e[0],t=>ai(new Array(e.coresCount).fill(t),e))),validatorsManager:ke.u32.asOpaque(),autoAccumulateServices:Ee(ke.sequenceVarLen(gi.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new fi(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const pi=128;class yi extends k{bandersnatch;ed25519;bls;metadata;static Codec=ke.Class(yi,{bandersnatch:ke.bytes(Oe).asOpaque(),ed25519:ke.bytes(cr).asOpaque(),bls:ke.bytes(Te).asOpaque(),metadata:ke.bytes(pi)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new yi(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var mi;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(mi||(mi={}));const bi=ke.bytes(Oe).asOpaque();class Ai extends k{kind;keys;tickets;static Codec=St(e=>ke.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Ne*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(se(t.kind)),t.kind===mi.Keys?e.sequenceFixLen(bi,t.keys):e.sequenceFixLen(Bt.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===mi.Keys){const s=t.sequenceFixLen(bi,r);return Ai.keys(xr(s,e))}if(s===mi.Tickets){const s=t.sequenceFixLen(Bt.Codec,r);return Ai.tickets(xr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==mi.Keys){if(r!==mi.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(Bt.Codec,e.epochLength)}else t.sequenceFixLen(bi,e.epochLength)}));static keys(e){return new Ai(mi.Keys,e,void 0)}static tickets(e){return new Ai(mi.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class Ii{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=ke.Class(Ii,{nextValidatorData:kr(yi.Codec),epochRoot:ke.bytes(Ue).asOpaque(),sealingKeySeries:Ai.Codec,ticketsAccumulator:Ee(ke.sequenceVarLen(Bt.Codec)).convert(B,ft)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new Ii(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}class vi extends k{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;storageUtilisationCount;static Codec=ke.Class(vi,{codeHash:ke.bytes(Ne).asOpaque(),balance:ke.u64,accumulateMinGas:ke.u64.convert(e=>e,wr),onTransferMinGas:ke.u64.convert(e=>e,wr),storageUtilisationBytes:ke.u64,storageUtilisationCount:ke.u32});static create(e){return new vi(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.storageUtilisationCount)}static calculateThresholdBalance(e,t){const r=ae(ne(100n),ne(10n*BigInt(e)),ne(1n*t));return r.overflow?ne(2n**64n-1n):r.value}constructor(e,t,r,s,i,n){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.storageUtilisationCount=n}}class wi extends k{hash;blob;static Codec=ke.Class(wi,{hash:ke.bytes(Ne).asOpaque(),blob:ke.blob});static create({hash:e,blob:t}){return new wi(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class Si extends k{key;value;static Codec=ke.Class(Si,{key:ke.bytes(Ne).asOpaque(),value:ke.blob});static create({key:e,value:t}){return new Si(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function Ei(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class Ci{hash;length;slots;constructor(e,t,r){this.hash=e,this.length=t,this.slots=r}static isRequested(e){return"slots"in e?0===e.slots.length:0===e.length}}var ki,xi,Bi;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(ki||(ki={}));class _i{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new _i(e,{kind:ki.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new _i(e,{kind:ki.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new _i(e,{kind:ki.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case ki.Provide:return this.action.preimage.hash;case ki.Remove:return this.action.hash;case ki.UpdateOrAdd:return this.action.item.hash}throw w(this.action)}get length(){switch(this.action.kind){case ki.Provide:return se(this.action.preimage.blob.length);case ki.Remove:return this.action.length;case ki.UpdateOrAdd:return this.action.item.length}throw w(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(xi||(xi={}));class Ri{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new Ri(e,{kind:xi.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new Ri(e,{kind:xi.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(Bi||(Bi={}));class Oi{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new Oi(e,{kind:Bi.Set,storage:t})}static remove({serviceId:e,key:t}){return new Oi(e,{kind:Bi.Remove,key:t})}get key(){return this.action.kind===Bi.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===Bi.Remove?null:this.action.storage.value}}const Ui=A.isSuite(u.W3F_DAVXY)?ke.u32.asOpaque():ke.varU32.convert(e=>se(e),e=>vr(e));class Ti{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=ke.Class(Ti,{blocks:ke.u32,tickets:ke.u32,preImages:ke.u32,preImagesSize:ke.u32,guarantees:ke.u32,assurances:ke.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new Ti(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.blocks=e,this.tickets=t,this.preImages=r,this.preImagesSize=s,this.guarantees=i,this.assurances=n}static empty(){const e=se(0);return new Ti(e,e,e,e,e,e)}}const Ni=ke.varU32.convert(e=>se(e),e=>te(e)),Di=ke.varU64.convert(e=>ne(e),e=>wr(e));class Mi{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=ke.Class(Mi,{dataAvailabilityLoad:ke.varU32,popularity:Ni,imports:Ni,exports:Ni,extrinsicSize:ke.varU32,extrinsicCount:Ni,bundleSize:ke.varU32,gasUsed:Di});static create(e){return new Mi(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,o,a){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=o,this.gasUsed=a}static empty(){const e=se(0),t=te(0),r=wr(0);return new Mi(e,t,t,t,e,t,e,r)}}class Pi{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=ke.Class(Pi,{providedCount:Ni,providedSize:ke.varU32,refinementCount:ke.varU32,refinementGasUsed:Di,imports:Ni,exports:Ni,extrinsicSize:ke.varU32,extrinsicCount:Ni,accumulateCount:ke.varU32,accumulateGasUsed:Di,onTransfersCount:ke.varU32,onTransfersGasUsed:Di});static create(e){return new Pi(e.providedCount,e.providedSize,e.refinementCount,e.refinementGasUsed,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.accumulateCount,e.accumulateGasUsed,e.onTransfersCount,e.onTransfersGasUsed)}constructor(e,t,r,s,i,n,o,a,c,l,h,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=o,this.extrinsicCount=a,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=h,this.onTransfersGasUsed=u}static empty(){const e=se(0),t=te(0),r=wr(0);return new Pi(t,e,e,r,t,t,e,t,e,r,e,r)}}class Li{current;previous;cores;services;static Codec=ke.Class(Li,{current:kr(Ti.Codec),previous:kr(Ti.Codec),cores:ci(Mi.Codec),services:ke.dictionary(Ui,Pi.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new Li(e.current,e.previous,e.cores,e.services)}constructor(e,t,r,s){this.current=e,this.previous=t,this.cores=r,this.services=s}}var Hi,Ki;(Ki=Hi||(Hi={}))[Ki.DuplicateService=0]="DuplicateService",Ki[Ki.NoService=1]="NoService",Ki[Ki.PreimageExists=2]="PreimageExists";class Vi extends k{serviceId;data;constructor(e,t){super(),this.serviceId=e,this.data=t}getInfo(){return this.data.info}getStorage(e){return this.data.storage.get(e)?.value??null}hasPreimage(e){return this.data.preimages.has(e)}getPreimage(e){return this.data.preimages.get(e)?.blob??null}getLookupHistory(e,t){const r=this.data.lookupHistory.get(e);return void 0===r?null:r.find(e=>e.length===t)?.slots??null}getEntries(){return{storageKeys:Array.from(this.data.storage.keys()),preimages:Array.from(this.data.preimages.keys()),lookupHistory:Array.from(this.data.lookupHistory.entries()).map(([e,t])=>({hash:e,length:t[0].length}))}}static copyFrom(e,t){const r=e.getInfo(),s=dt.new(),i=dt.new(),n=dt.new();for(const r of t.preimages){const t=e.getPreimage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected preimage: ${r}`);s.set(r,wi.create({hash:r,blob:t}))}for(const{hash:r,length:s}of t.lookupHistory){const t=e.getLookupHistory(r,s);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected lookupHistory: ${r}, ${s}`);const i=n.get(r)??[];i.push(new Ci(r,s,t)),n.set(r,i)}for(const r of t.storageKeys){const t=e.getStorage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected storage: ${r}`);i.set(r,Si.create({key:r,value:t}))}return new Vi(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class Qi extends k{static create(e){return new Qi(e)}static partial(e,t){const r=Qi.empty(e);return Object.assign(r,t),r}static copyFrom(e,t){const r=new Map;for(const[s,i]of t.entries()){const t=e.getService(s);if(null===t)throw new Error(`Expected service ${s} to be part of the state!`);const n=Vi.copyFrom(t,i);r.set(s,n)}return Qi.create({availabilityAssignment:e.availabilityAssignment,accumulationQueue:e.accumulationQueue,designatedValidatorData:e.designatedValidatorData,nextValidatorData:e.nextValidatorData,currentValidatorData:e.currentValidatorData,previousValidatorData:e.previousValidatorData,disputesRecords:e.disputesRecords,timeslot:e.timeslot,entropy:e.entropy,authPools:e.authPools,authQueues:e.authQueues,recentBlocks:e.recentBlocks,statistics:e.statistics,recentlyAccumulated:e.recentlyAccumulated,ticketsAccumulator:e.ticketsAccumulator,sealingKeySeries:e.sealingKeySeries,epochRoot:e.epochRoot,privilegedServices:e.privilegedServices,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.keys()),preimages:Array.from(r.preimages.keys()),lookupHistory:Array.from(r.lookupHistory).flatMap(([e,t])=>t.map(t=>({hash:e,length:t.length})))});return e}applyUpdate(e){const{servicesRemoved:t,servicesUpdates:r,preimages:s,storage:i,...n}=e;let o;return Object.assign(this,n),o=this.updateServices(r),o.isError?o:(o=this.updatePreimages(s),o.isError?o:(o=this.updateStorage(i),o.isError?o:(this.removeServices(t),T.ok(_))))}removeServices(e){for(const t of e??[])I(this.services.has(t),`Attempting to remove non-existing service: ${t}`),this.services.delete(t)}updateStorage(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e}=r,s=this.services.get(t);if(void 0===s)return T.error(Hi.NoService,`Attempting to update storage of non-existing service: ${t}`);e===Bi.Set?s.data.storage.set(r.storage.key,r.storage):e===Bi.Remove?(I(s.data.storage.has(r.key),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(r.key)):w(e)}return T.ok(_)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return T.error(Hi.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===ki.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return T.error(Hi.PreimageExists,`Overwriting existing preimage at ${t}: ${s}`);if(e.data.preimages.set(s.hash,s),null!==i){const t=e.data.lookupHistory.get(s.hash),r=se(s.blob.length),n=new Ci(s.hash,r,Ei([i]));if(void 0===t)e.data.lookupHistory.set(s.hash,[n]);else{const e=t.map(e=>e.length).indexOf(r);t.splice(e,-1===e?0:1,n)}}}else if(s===ki.Remove){const{hash:t,length:s}=r;e.data.preimages.delete(t);const i=e.data.lookupHistory.get(t)??[],n=i.map(e=>e.length).indexOf(s);-1!==n&&i.splice(n,1)}else if(s===ki.UpdateOrAdd){const{item:t}=r,s=e.data.lookupHistory.get(t.hash)??[],i=s.map(e=>e.length).indexOf(t.length),n=-1===i?0:1;s.splice(i,n,t),e.data.lookupHistory.set(t.hash,s)}else w(s)}return T.ok(_)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===xi.Create){const{lookupHistory:e}=r;if(this.services.has(t))return T.error(Hi.DuplicateService,`${t} already exists!`);this.services.set(t,new Vi(t,{info:s,preimages:dt.new(),storage:dt.new(),lookupHistory:dt.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===xi.Update){const e=this.services.get(t);if(void 0===e)return T.error(Hi.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else w(e)}return T.ok(_)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;services;recentServiceIds(){return Array.from(this.services.keys())}getService(e){return this.services.get(e)??null}constructor(e){super(),this.availabilityAssignment=e.availabilityAssignment,this.designatedValidatorData=e.designatedValidatorData,this.nextValidatorData=e.nextValidatorData,this.currentValidatorData=e.currentValidatorData,this.previousValidatorData=e.previousValidatorData,this.disputesRecords=e.disputesRecords,this.timeslot=e.timeslot,this.entropy=e.entropy,this.authPools=e.authPools,this.authQueues=e.authQueues,this.recentBlocks=e.recentBlocks,this.statistics=e.statistics,this.accumulationQueue=e.accumulationQueue,this.recentlyAccumulated=e.recentlyAccumulated,this.ticketsAccumulator=e.ticketsAccumulator,this.sealingKeySeries=e.sealingKeySeries,this.epochRoot=e.epochRoot,this.privilegedServices=e.privilegedServices,this.services=e.services}static empty(e){return new Qi({availabilityAssignment:ai(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),nextValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),currentValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),previousValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),disputesRecords:ui.create({goodSet:mt.fromSortedArray(di,[]),badSet:mt.fromSortedArray(di,[]),wonkySet:mt.fromSortedArray(di,[]),punishSet:mt.fromSortedArray(di,[])}),timeslot:Ar(0),entropy:pt.fill(()=>M.zero(Ne).asOpaque(),4),authPools:ai(Array.from({length:e.coresCount},()=>[]),e),authQueues:ai(Array.from({length:e.coresCount},()=>pt.fill(()=>M.zero(Ne).asOpaque(),80)),e),recentBlocks:[],statistics:Li.create({current:Cr(Array.from({length:e.validatorsCount},()=>Ti.empty()),e),previous:Cr(Array.from({length:e.validatorsCount},()=>Ti.empty()),e),cores:ai(Array.from({length:e.coresCount},()=>Mi.empty()),e),services:new Map}),accumulationQueue:xr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:xr(Array.from({length:e.epochLength},()=>gt.new()),e),ticketsAccumulator:[],sealingKeySeries:Ai.keys(xr(Array.from({length:e.epochLength},()=>M.zero(Oe).asOpaque()),e)),epochRoot:M.zero(Ue).asOpaque(),privilegedServices:fi.create({manager:vr(0),authManager:ai(new Array(e.coresCount).fill(vr(0)),e),validatorsManager:vr(0),autoAccumulateServices:[]}),services:new Map})}}const Fi=ke.object({storageKeys:ke.sequenceVarLen(ke.bytes(Ne).asOpaque()),preimages:ke.sequenceVarLen(ke.bytes(Ne).asOpaque()),lookupHistory:ke.sequenceVarLen(ke.object({hash:ke.bytes(Ne).asOpaque(),length:ke.u32}))});ke.dictionary(ke.u32.asOpaque(),Fi,{sortKeys:(e,t)=>e-t});class Gi extends k{report;dependencies;static Codec=ke.Class(Gi,{report:Gr.Codec,dependencies:Et(ke.bytes(Ne).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new Gi(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var $i,ji,qi;!function(e){e[e.Unused=0]="Unused",e[e.Alpha=1]="Alpha",e[e.Phi=2]="Phi",e[e.Beta=3]="Beta",e[e.Gamma=4]="Gamma",e[e.Psi=5]="Psi",e[e.Eta=6]="Eta",e[e.Iota=7]="Iota",e[e.Kappa=8]="Kappa",e[e.Lambda=9]="Lambda",e[e.Rho=10]="Rho",e[e.Tau=11]="Tau",e[e.Chi=12]="Chi",e[e.Pi=13]="Pi",e[e.Theta=14]="Theta",e[e.Xi=15]="Xi",e[e.Delta=255]="Delta"}($i||($i={})),function(e){function t(e,t){const r=M.zero(Ne);let s=0;for(const i of ce(e))r.raw[s]=i,r.raw[s+1]=t.raw[s/2],s+=2;const i=s/2;return r.raw.set(t.raw.subarray(i,Ne-i),s),r.asOpaque()}e.index=function(e){const t=M.zero(Ne);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=M.zero(Ne);t.raw[0]=$i.Delta;let r=1;for(const s of ce(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){const s=M.zero(Ne);return s.raw.set(ce(se(2**32-1)),0),s.raw.set(r.raw.subarray(0,28),4),t(e,s)},e.servicePreimage=function(e,r){const s=M.zero(Ne);return s.raw.set(ce(se(2**32-2)),0),s.raw.set(r.raw.subarray(1,29),4),t(e,s)},e.serviceLookupHistory=function(e,r,s){const i=Ge(r),n=M.zero(Ne);return n.raw.set(ce(s),0),n.raw.set(i.raw.subarray(2,30),4),t(e,n)},e.serviceNested=t}(ji||(ji={})),function(e){e.authPools={key:ji.index($i.Alpha),Codec:ci(Et(ke.bytes(Ne).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:ji.index($i.Phi),Codec:ci(Ct(ke.bytes(Ne).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:ji.index($i.Beta),Codec:Et(oi.Codec,{minLength:0,maxLength:8,typicalLength:8}),extract:e=>e.recentBlocks},e.safrole={key:ji.index($i.Gamma),Codec:Ii.Codec,extract:e=>Ii.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:ji.index($i.Psi),Codec:ui.Codec,extract:e=>e.disputesRecords},e.entropy={key:ji.index($i.Eta),Codec:Ct(ke.bytes(Ne).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:ji.index($i.Iota),Codec:kr(yi.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:ji.index($i.Kappa),Codec:kr(yi.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:ji.index($i.Lambda),Codec:kr(yi.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:ji.index($i.Rho),Codec:ci(ke.optional(ni.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:ji.index($i.Tau),Codec:ke.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:ji.index($i.Chi),Codec:fi.Codec,extract:e=>e.privilegedServices},e.statistics={key:ji.index($i.Pi),Codec:Li.Codec,extract:e=>e.statistics},e.accumulationQueue={key:ji.index($i.Theta),Codec:Br(Ee(ke.sequenceVarLen(Gi.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:ji.index($i.Xi),Codec:Br(ke.sequenceVarLen(ke.bytes(Ne).asOpaque()).convert(e=>Array.from(e),e=>gt.from(e))),extract:e=>e.recentlyAccumulated},e.serviceData=e=>({key:ji.serviceInfo(e),Codec:vi.Codec}),e.serviceStorage=(e,t)=>({key:ji.serviceStorage(e,t),Codec:zi}),e.servicePreimages=(e,t)=>({key:ji.servicePreimage(e,t),Codec:zi}),e.serviceLookupHistory=(e,t,r)=>({key:ji.serviceLookupHistory(e,t,r),Codec:Ee(ke.sequenceVarLen(ke.u32))})}(qi||(qi={}));const zi=Se.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(M.fromBlob(t.raw,t.raw.length)),e=>D.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var Wi;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(Wi||(Wi={}));const Ji=D.empty();class Yi{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new Yi(e,t,r)}static new(e,t,r=[]){return new Yi(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}[N](){return this.backend}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(qi.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new Xi(e,t,e=>this.retrieveOptional(e)))}retrieve({key:e,Codec:t},r){const s=this.backend.get(e);if(null===s)throw new Error(`Required state entry for ${r} is missing!. Accessing key: ${e}`);return ue.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return ue.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(qi.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(qi.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(qi.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(qi.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(qi.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(qi.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(qi.timeslot,"timeslot")}get entropy(){return this.retrieve(qi.entropy,"entropy")}get authPools(){return this.retrieve(qi.authPools,"authPools")}get authQueues(){return this.retrieve(qi.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(qi.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(qi.statistics,"statistics")}get accumulationQueue(){return this.retrieve(qi.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(qi.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(qi.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(qi.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(qi.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(qi.privilegedServices,"privilegedServices")}}class Xi{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){return this.retrieveOptional(qi.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(qi.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(qi.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(qi.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:Ei(r.map(Ar))}}const Zi=31;var en;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(en||(en={}));class tn{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?en.EmbedLeaf:en.Leaf:en.Branch}asBranchNode(){return I(this.getNodeType()===en.Branch),new rn(this)}asLeafNode(){return I(this.getNodeType()!==en.Branch),new sn(this)}toString(){return D.blobFrom(this.raw).toString()}}class rn{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new tn;return r.raw.set(e.raw,0),r.raw.set(t.raw,Ne),r.raw[0]&=127,new rn(r)}getLeft(){return M.fromBlob(this.node.raw.subarray(0,Ne),Ne).asOpaque()}getRight(){return M.fromBlob(this.node.raw.subarray(Ne),Ne).asOpaque()}}class sn{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new tn;return t.length<=Ne?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,Zi),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,Zi),1),s.raw.set(r().raw,32)),new sn(s)}getKey(){return M.fromBlob(this.node.raw.subarray(1,32),Zi).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===en.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return D.blobFrom(this.node.raw.subarray(Ne,Ne+e))}getValueHash(){return M.fromBlob(this.node.raw.subarray(Ne),Ne).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}class nn{hasher;nodes=dt.new();constructor(e){this.hasher=e}get(e){return nn.withHashCompat(e,e=>this.nodes.get(e)??null)}hashNode(e){return this.hasher.hashConcat(e.raw)}*leaves(){for(const e of this.nodes.values())e.getNodeType()!==en.Branch&&(yield e.asLeafNode())}static withHashCompat(e,t){const r=e.raw[0];e.raw[0]&=127;const s=t(e);return e.raw[0]=r,s}}class on extends nn{remove(e){return nn.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return nn.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class an{nodes;root;static empty(e){return new an(new on(e))}static computeStateRoot(e,t){return an.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new on(e);for(const e of t)r=cn(r,s,e);return new an(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=sn.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=cn(this.root,this.nodes,s),s}remove(e){throw new Error("Removing from the trie not implemented yet.")}getRootNode(){return this.root}getRootHash(){return null===this.root?M.zero(Ne).asOpaque():this.nodes.hashNode(this.root)}toString(){return un(this.root,this.nodes)}}function cn(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new ln;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==en.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),o=hn(r,s.bitIndex),a=o?e.getRight():e.getLeft();s.branchingHistory.push([e,n,o]);const c=t.get(a);if(null===c){if(a.isEqualTo(M.zero(Ne)))return s;throw new Error(`Missing trie node '${a}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=a,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,o]=r;const a=n.getKey(),c=t.insert(s.node);if(a.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(o),[s.node,c];const l=[];let h=hn(i,e.bitIndex);for(;e.bitIndex<248;){h=hn(i,e.bitIndex);const t=hn(a,e.bitIndex);if(h!==t)break;l.push(t),e.bitIndex+=1}const u=M.zero(Ne).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!h&&(o=t.hashNode(n.node));let d=h?rn.fromSubNodes(o,c):rn.fromSubNodes(c,o),g=t.insert(d.node),f=l.pop();for(;void 0!==f;)d=f?rn.fromSubNodes(u,g):rn.fromSubNodes(g,u),g=t.insert(d.node),f=l.pop();return[d.node,g]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[o,a]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?rn.fromSubNodes(e.getLeft(),a):rn.fromSubNodes(a,e.getRight());a=t.insert(c.node),o=c.node,n=s.branchingHistory.pop()}return o}class ln{branchingHistory=[];bitIndex=0;leafToReplace}function hn(e,t){I(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function un(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===en.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),o=un(t.get(s),t),a=un(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(o)}\n\t-- ${i}: ${n(a)}\n`}const r=e.asLeafNode(),s=r.getValueLength(),i=s>0?`'${r.getValue()}'(len:${s})`:`'<hash>${r.getValueHash()}'`;return`\nLeaf('${r.getKey().toString()}',${i})`}const dn={hashConcat:(e,t=[])=>Fe([e,...t])};class gn{entries;static serializeInMemory(e,t){return new gn({full:!0,data:fn(e,t)})}static fromDictionaryUnsafe(e){return new gn({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new gn({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}[N](){return this.entries.data}getTrie(){if(null===this.trieCache){const e=an.empty(dn);for(const[t,r]of this.entries.data)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}get(e){return this.entries.data.get(e)??null}applyUpdate(e){this.trieCache=null;for(const[t,r,s]of e)t===Wi.Insert?this.entries.data.set(r,s):t===Wi.Remove?this.entries.data.delete(r):w(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function fn(e,t){const r=dt.new();function s(s){r.set(s.key,me.encodeObject(s.Codec,s.extract(t),e))}s(qi.authPools),s(qi.authQueues),s(qi.recentBlocks),s(qi.safrole),s(qi.disputesRecords),s(qi.entropy),s(qi.designatedValidators),s(qi.currentValidators),s(qi.previousValidators),s(qi.availabilityAssignment),s(qi.timeslot),s(qi.privilegedServices),s(qi.statistics),s(qi.accumulationQueue),s(qi.recentlyAccumulated);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=qi.serviceData(e);r.set(t,me.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=qi.servicePreimages(e,t.hash);r.set(s,me.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=qi.serviceStorage(e,t.key);r.set(s,me.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=qi.serviceLookupHistory(e,s.hash,s.length);r.set(t,me.encodeObject(i,s.slots.slice()))}}return r}const pn=ke.object({hash:ke.bytes(Ne).asOpaque(),length:ke.u32,slots:Ee(ke.sequenceVarLen(ke.u32.asOpaque())).convert(B,Ei)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new Ci(e,t,r)),yn=ke.object({key:ke.bytes(Ne).asOpaque(),data:ke.sequenceVarLen(pn)}),mn=ke.sequenceVarLen(yn).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=dt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class bn extends Vi{static Codec=ke.Class(bn,{serviceId:ke.u32.asOpaque(),data:ke.object({info:vi.Codec,preimages:kt(wi.Codec,e=>e.hash),lookupHistory:mn,storage:kt(Si.Codec,e=>e.key)})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new bn(e,t)}}var An,In,vn;ke.Class(Qi,{authPools:qi.authPools.Codec,authQueues:qi.authQueues.Codec,recentBlocks:qi.recentBlocks.Codec,nextValidatorData:kr(yi.Codec),epochRoot:ke.bytes(Ue).asOpaque(),sealingKeySeries:Ai.Codec,ticketsAccumulator:Ee(ke.sequenceVarLen(Bt.Codec)).convert(e=>e,ft),disputesRecords:qi.disputesRecords.Codec,entropy:qi.entropy.Codec,designatedValidatorData:qi.designatedValidators.Codec,currentValidatorData:qi.currentValidators.Codec,previousValidatorData:qi.previousValidators.Codec,availabilityAssignment:qi.availabilityAssignment.Codec,timeslot:qi.timeslot.Codec,privilegedServices:qi.privilegedServices.Codec,statistics:qi.statistics.Codec,accumulationQueue:qi.accumulationQueue.Codec,recentlyAccumulated:qi.recentlyAccumulated.Codec,services:ke.dictionary(ke.u32.asOpaque(),bn.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(An||(An={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(In||(In={}));class wn{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return T.error(In.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new tn(t.raw);if(e.getNodeType()===en.Branch)return T.error(In.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return T.ok(new wn(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=bt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:vn.EmbeddedValue,value:e.getValue()}:{kind:vn.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===vn.EmbeddedValue?t.value:t.kind===vn.DbKey?D.blobFrom(this.db.get(t.key)):void w(t)}getStateRoot(){return an.computeStateRoot(dn,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(vn||(vn={}));class Sn{spec;root;states;values;constructor(e,t){this.spec=e,this.root=t,this.states=this.root.subDb("states"),this.values=this.root.subDb("values")}async insertState(e,t){const r=an.empty(dn);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[Wi.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===Wi.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===Wi.Remove?t.remove(i.asOpaque()):w(e);const i=D.blobFromParts(Array.from(t.nodes.leaves()).map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),o=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([o,n])}catch(e){return console.error(e),T.error(An.Commit)}return T.ok(_)}async updateAndSetState(e,t,r){const s=an.fromLeaves(dn,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[Wi.Insert,r.key,me.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,qi.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,qi.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,qi.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return Ii.create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s});if([e,t,r,s].some(e=>void 0!==e))throw new Error("SafroleData needs to be updated all at once!")}(t.nextValidatorData,t.epochRoot,t.sealingKeySeries,t.ticketsAccumulator);void 0!==s&&(yield r(s,qi.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,qi.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,qi.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,qi.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,qi.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,qi.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,qi.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,qi.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,qi.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,qi.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,qi.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,qi.recentlyAccumulated))}(e,t);const r=(t,r)=>me.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=qi.serviceData(s);if(yield[Wi.Insert,e.key,t(e.Codec,r.account)],r.kind===xi.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=qi.serviceLookupHistory(s,e.hash,e.length);yield[Wi.Insert,i.key,t(i.Codec,e.slots)]}}}(t.servicesUpdates,r),yield*function*(e,t){for(const{action:r,serviceId:s}of e??[])switch(r.kind){case ki.Provide:{const{hash:e,blob:i}=r.preimage,n=qi.servicePreimages(s,e);if(yield[Wi.Insert,n.key,i],null!==r.slot){const n=qi.serviceLookupHistory(s,e,se(i.length));yield[Wi.Insert,n.key,t(n.Codec,Ei([r.slot]))]}break}case ki.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,o=qi.serviceLookupHistory(s,e,i);yield[Wi.Insert,o.key,t(o.Codec,n)];break}case ki.Remove:{const{hash:e,length:t}=r,i=qi.servicePreimages(s,e);yield[Wi.Remove,i.key,Ji];const n=qi.serviceLookupHistory(s,e,t);yield[Wi.Remove,n.key,Ji];break}default:w(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case Bi.Set:{const e=qi.serviceStorage(r,t.storage.key);yield[Wi.Insert,e.key,t.storage.value];break}case Bi.Remove:{const e=qi.serviceStorage(r,t.key);yield[Wi.Remove,e.key,Ji];break}default:w(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=qi.serviceData(t);yield[Wi.Remove,e.key,Ji]}}(t.servicesRemoved)}(this.spec,r);return await this.updateAndCommit(e,s,i)}async getStateRoot(e){return e.backend.getStateRoot()}getState(e){const t=this.states.get(e.raw);if(void 0===t)return null;const r=this.values,s=wn.fromLeavesBlob(D.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${D.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${U(s)}`);return Yi.new(this.spec,s.ok)}}const En=t(import.meta.url)("node:events"),Cn=2**32,kn=Js.new(void 0,"state-machine/port");class xn{port;listeners=new En.EventEmitter;responseListeners=new En.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw kn.error(`[${this.constructor.name}] Failed to dispatch a message: ${t}: ${JSON.stringify(e)}`),t}})}async sendRequest(e,t,r,s){const[i,n]=this.prepareRequest(e,t,r);return this.postMessage(i,s),n}sendSignal(e,t,r,s){this.messageId=(this.messageId+1)%Cn,this.messageId>>>=0,this.postMessage({kind:"signal",name:t,id:this.messageId,localState:e,data:r},s)}prepareRequest(e,t,r){this.messageId+=1;const s=new Promise((e,t)=>{this.responseListeners.once(Bn(this.messageId),(r,s)=>null!==r?t(r):e(s))});return[{kind:"request",id:this.messageId,name:t,localState:e,data:r},s]}respond(e,t,r){I("request"===t.kind),this.postMessage({kind:"response",id:t.id,name:t.name,data:r,localState:e})}close(){this.cleanup("closing"),this.listeners.removeAllListeners(),this.port.close()}postMessage(e,t){try{this.port.postMessage(e,t)}catch(t){throw kn.error(`[${this.constructor.name}] Failed to post a message: ${t}: ${JSON.stringify(e)}`),t}}dispatchPortMessage(e){if(!function(e){return null!==e&&"object"==typeof e&&"kind"in e&&"string"==typeof e.kind&&"id"in e&&"number"==typeof e.id&&"name"in e&&"string"==typeof e.name&&"data"in e&&"localState"in e&&"string"==typeof e.localState}(e))throw new Error(`Invalid message: ${JSON.stringify(e)}.`);switch(e.kind){case"response":I(-1!==this.responseListeners.eventNames().indexOf(Bn(e.id))),this.responseListeners.emit(Bn(e.id),null,e.data,e.name,e.localState,e);break;case"signal":this.listeners.emit("signal",e.name,e.data,e.localState,e);break;case"request":this.listeners.emit("request",e.name,e.data,e.localState,e);break;case"subscription":case"subscribe":throw new Error("unimplemented");default:throw new Error(`Unexpected message: "${e.kind}"`)}}cleanup(e){const t=this.responseListeners.eventNames();for(const r in t)this.responseListeners.emit(r,new Error(`port is ${e}`))}}function Bn(e){return`req:${e}`}const _n=Js.new(void 0,"state-machine"),Rn="channel";class On{machine;port;constructor(e,t){this.machine=e,this.port=t,t.listeners.on("signal",(e,t,r)=>{try{this.dispatchSignal(e,t)}catch(t){throw _n.error(`[${this.constructor.name}] Unable to dispatch signal (${e}): ${t}. ${this.stateInfo(r)}`),t}}),t.listeners.on("request",async(e,t,r,s)=>{try{await this.dispatchRequest(e,t,s)}catch(t){throw _n.error(`[${this.constructor.name}] Unable to dispatch request (${e}): ${t}. ${this.stateInfo(r)}`),t}})}sendSignal(e,t){this.port.sendSignal(this.currentState().stateName,e,t)}async sendRequest(e,t){return this.port.sendRequest(this.currentState().stateName,e,t)}close(){this.port.close()}getState(e){return this.machine.getState(e)}currentState(){return this.machine.currentState()}async waitForState(e){return await this.machine.waitForState(e),this.transitionTo()}async doUntil(e,t){const r={isDone:!1},s=this.waitForState(e).then(()=>{r.isDone=!0});return await t(this.currentState(),this,()=>r.isDone),await s,this.transitionTo()}transition(e){const t=e(this.currentState(),this);return this.machine.transition(t.state,t.data),this.transitionTo()}stateInfo(e){return` (local state: "${this.currentState()}", remote state: "${e}")`}async dispatchRequest(e,t,r){const s=this.currentState(),i=s.requestHandlers.get(e);if(void 0===i)throw new Error(`Missing request handler for "${e}"`);const n=await i(t),o=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!o)return this.port.respond(s.stateName,r,n.response);_n.warn(`Ignoring obsolete response for an old request: "${e}"`)}dispatchSignal(e,t){const r=this.currentState().signalListeners.get(e);if(void 0===r)throw new Error(`Unexpected signal "${e}"`);const s=r(t);void 0!==s&&this.machine.transition(s.state,s.data)}transitionTo(){return _n.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new Ys.MessageChannel,s=new xn(r.port2),i=e.currentState().stateName,[n,o]=s.prepareRequest(i,Rn,r.port1);t.postMessage(n,[r.port1]);try{await o}catch(e){_n.error(JSON.stringify(e))}return new On(e,s)}static async receiveChannel(e,t){if(null===t)throw new Error("This code is expected to be run in a worker.");const r=new Promise((r,s)=>{t.once("message",t=>{try{I("request"===t.kind,"The initial message should be a request with channel."),I(t.name===Rn),I(t.data instanceof Ys.MessagePort);const s=new xn(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new On(e,s)}}const Un=Symbol(),Tn=Symbol();class Nn{emitter=new En.EventEmitter;emit(e){this.emitter.emit(Un,e)}on(e){return this.emitter.on(Un,e),this}once(e){return this.emitter.once(Un,e),this}onceDone(e){return this.emitter.once(Tn,e),this}markDone(){this.emitter.emit(Tn),this.emitter.removeAllListeners(Un),this.emitter.removeAllListeners(Tn)}}class Dn{name;state;allStates;stateListeners=new En.EventEmitter;constructor(e,t,r){this.name=e,this.state=t,this.allStates=new Map;for(const e of r)this.allStates.set(e.stateName,e)}getState(e){const t=this.allStates.get(e);return I(void 0!==t,`Unable to retrieve state object for ${e}.`),t}currentState(){return this.state}waitForState(e){if(this.state.stateName===e)throw new Error(`Attempting to await a state that is already active: ${e}`);return new Promise(t=>{this.stateListeners.once(e,t)})}transition(e,t){if(this.state.stateName===e)throw new Error("Attempting transition to already active state!");if(!this.state.canTransitionTo(e))throw new Error(`Unallowed transition from ${this.state} to ${e}`);const r=this.allStates.get(e);if(void 0===r)throw new Error(`Unavailable state: ${e}`);r.onActivation(t);const s=this.transitionTo(r);return s.stateListeners.emit(e,s),s}transitionTo(e){return this.state=e,this}}const Mn=Js.new(void 0,"state-machine/state");class Pn{stateName;signalListeners;requestHandlers;allowedTransitions;data=null;constructor({name:e,signalListeners:t={},requestHandlers:r={},allowedTransitions:s=[]}){this.stateName=e,this.allowedTransitions=s,this.signalListeners=new Map(Object.entries(t)),this.requestHandlers=new Map(Object.entries(r))}onActivation(e){Mn.trace(`[${this.constructor.name}] Changing state to: ${this}`),this.data=e}canTransitionTo(e){return-1!==this.allowedTransitions.indexOf(e)}toString(){return`<State ${this.stateName}>`}}class Ln extends Pn{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class Hn extends Pn{readyName;constructor(e){super({name:"init(main)",allowedTransitions:[e]}),this.readyName=e}sendConfig(e,t){return e.sendSignal("config",t),{state:this.readyName,data:t}}}class Kn extends Pn{workerReadyName;handleConfig;constructor(e,t){super({name:"init(worker)",allowedTransitions:[e],signalListeners:{config:e=>this.onConfig(e)}}),this.workerReadyName=e,this.handleConfig=t}onConfig(e){return{state:this.workerReadyName,data:this.handleConfig(e)}}}async function Vn(e,t,r,s){const i=new Ys.Worker(e),n=function(e,t,r){const s=new Hn(t),i=new Ln;return new Dn(e,s,[s,r,i])}(`main->${r}`,r,s),o=await On.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${o.currentState()}`),o}const Qn=4294967295,Fn=4294967296,Gn=4096,$n=(I(!0,"incorrect minimal allocation shift"),7),jn=Gn>>$n,qn=1048575,zn=1048576,Wn=e=>v(e,e>=0&&e<=Qn,`Incorrect memory index: ${e}!`),Jn=e=>v(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var Yn,Xn;(Xn=Yn||(Yn={}))[Xn.OK=255]="OK",Xn[Xn.HALT=0]="HALT",Xn[Xn.PANIC=1]="PANIC",Xn[Xn.FAULT=2]="FAULT",Xn[Xn.HOST=3]="HOST",Xn[Xn.OOG=4]="OOG";const Zn=e=>se(e);var eo,to;!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(eo||(eo={}));class ro{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return I(e>=0,`index (${e}) cannot be a negative number`),Math.min(this.lookupTableForward[e]??0,25)}buildLookupTableForward(e){const t=new Uint8Array(e.bitLength);let r=0;for(let s=e.bitLength-1;s>=0;s--)e.isSet(s)?r=0:r++,t[s]=r;return t}static empty(){return new ro(z.empty(0))}}!function(e){e[e.NO_ARGUMENTS=0]="NO_ARGUMENTS",e[e.ONE_IMMEDIATE=1]="ONE_IMMEDIATE",e[e.TWO_IMMEDIATES=2]="TWO_IMMEDIATES",e[e.ONE_OFFSET=3]="ONE_OFFSET",e[e.ONE_REGISTER_ONE_IMMEDIATE=4]="ONE_REGISTER_ONE_IMMEDIATE",e[e.ONE_REGISTER_TWO_IMMEDIATES=5]="ONE_REGISTER_TWO_IMMEDIATES",e[e.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET=6]="ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET",e[e.TWO_REGISTERS=7]="TWO_REGISTERS",e[e.TWO_REGISTERS_ONE_IMMEDIATE=8]="TWO_REGISTERS_ONE_IMMEDIATE",e[e.TWO_REGISTERS_ONE_OFFSET=9]="TWO_REGISTERS_ONE_OFFSET",e[e.TWO_REGISTERS_TWO_IMMEDIATES=10]="TWO_REGISTERS_TWO_IMMEDIATES",e[e.THREE_REGISTERS=11]="THREE_REGISTERS",e[e.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE=12]="ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE"}(to||(to={}));class so{u32;i32;u64;i64;view;bytes;constructor(){const e=new ArrayBuffer(8);this.u32=new Uint32Array(e),this.i32=new Int32Array(e),this.u64=new BigUint64Array(e),this.i64=new BigInt64Array(e),this.view=new DataView(e),this.bytes=new Uint8Array(e)}setBytes(e){const t=e.length,r=t>0?128&e[t-1]:0,s=Math.min(t,8),i=0!==r?255:0;for(let t=0;t<s;t++)this.view.setUint8(t,e[t]);for(let e=t;e<8;e++)this.view.setUint8(e,i)}getUnsigned(){return this.u32[0]}getSigned(){return this.i32[0]}getU32(){return this.u32[0]}getI32(){return this.i32[0]}getU64(){return this.u64[0]}getI64(){return this.i64[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,4)}getExtendedBytesAsLittleEndian(){return this.bytes}}class io{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,I(104===e.length,"Invalid size of registers array."),this.asSigned=new BigInt64Array(e.buffer,e.byteOffset),this.asUnsigned=new BigUint64Array(e.buffer,e.byteOffset)}static fromBytes(e){return I(104===e.length,"Invalid size of registers array."),new io(e)}getBytesAsLittleEndian(e,t){const r=e<<3;return this.bytes.subarray(r,r+t)}getAllBytesAsLittleEndian(){return this.bytes}copyFrom(e){const t=e instanceof BigUint64Array?e:e.asUnsigned;this.asUnsigned.set(t)}reset(){for(let e=0;e<13;e++)this.asUnsigned[e]=0n}getLowerU32(e){return Number(0xffffffffn&this.asUnsigned[e])}getLowerI32(e){return 0|Number(this.getLowerU32(e))}setU32(e,t){this.asUnsigned[e]=no(t)}setI32(e,t){this.asSigned[e]=no(t)}getU64(e){return this.asUnsigned[e]}getI64(e){return this.asSigned[e]}setU64(e,t){this.asUnsigned[e]=t}setI64(e,t){this.asSigned[e]=t}getAllU64(){return this.asUnsigned}}function no(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}class oo{byte=new Int8Array(1);setByte(e){this.byte[0]=e}getHighNibble(){return(240&this.byte[0])>>>4}getLowNibble(){return 15&this.byte[0]}getHighNibbleAsRegisterIndex(){return Math.min(this.getHighNibble(),12)}getLowNibbleAsRegisterIndex(){return Math.min(this.getLowNibble(),12)}getHighNibbleAsLength(){return Math.min(this.getHighNibble(),4)}getLowNibbleAsLength(){return Math.min(this.getLowNibble(),4)}}class ao{nibblesDecoder=new oo;offsetDecoder=new so;code=new Uint8Array;mask=ro.empty();reset(e,t){this.code=e,this.mask=t}fillArgs(e,t){const r=1+this.mask.getNoOfBytesToNextInstruction(e+1);switch(t.noOfBytesToSkip=r,t.type){case to.NO_ARGUMENTS:break;case to.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case to.THREE_REGISTERS:{const r=this.code[e+1],s=this.code[e+2];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),this.nibblesDecoder.setByte(s),t.thirdRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case to.TWO_REGISTERS_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));t.immediateDecoder.setBytes(this.code.subarray(i,n));break}case to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,o));const a=e+2+i,c=a+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(a,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case to.TWO_REGISTERS_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));this.offsetDecoder.setBytes(this.code.subarray(i,n)),t.nextPc=e+this.offsetDecoder.getSigned();break}case to.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case to.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const o=this.offsetDecoder.getSigned();t.nextPc=e+o;break}case to.ONE_REGISTER_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2)),o=this.code.subarray(i,n);t.immediateDecoder.setBytes(o);break}case to.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case to.ONE_REGISTER_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case to.TWO_REGISTERS_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=this.code[e+2];this.nibblesDecoder.setByte(i);const n=this.nibblesDecoder.getLowNibbleAsLength(),o=e+3,a=o+n,c=this.code.subarray(o,a);t.firstImmediateDecoder.setBytes(c);const l=a,h=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,h);t.secondImmediateDecoder.setBytes(u);break}case to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const s=e+2,i=s+8,n=this.code.subarray(s,i);t.immediateDecoder.setBytes(n);break}}}}class co{unsignedImmediate;bytes;constructor(){const e=new ArrayBuffer(8);this.unsignedImmediate=new BigUint64Array(e),this.bytes=new Uint8Array(e)}setBytes(e){let t=0;for(;t<e.length;t++)this.bytes[t]=e[t];for(;t<8;t++)this.bytes[t]=0}getValue(){return this.unsignedImmediate[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,8)}}const lo=Object.keys(to).length/2;var ho;!function(e){e[e.TRAP=0]="TRAP",e[e.FALLTHROUGH=1]="FALLTHROUGH",e[e.ECALLI=10]="ECALLI",e[e.LOAD_IMM_64=20]="LOAD_IMM_64",e[e.STORE_IMM_U8=30]="STORE_IMM_U8",e[e.STORE_IMM_U16=31]="STORE_IMM_U16",e[e.STORE_IMM_U32=32]="STORE_IMM_U32",e[e.STORE_IMM_U64=33]="STORE_IMM_U64",e[e.JUMP=40]="JUMP",e[e.JUMP_IND=50]="JUMP_IND",e[e.LOAD_IMM=51]="LOAD_IMM",e[e.LOAD_U8=52]="LOAD_U8",e[e.LOAD_I8=53]="LOAD_I8",e[e.LOAD_U16=54]="LOAD_U16",e[e.LOAD_I16=55]="LOAD_I16",e[e.LOAD_U32=56]="LOAD_U32",e[e.LOAD_I32=57]="LOAD_I32",e[e.LOAD_U64=58]="LOAD_U64",e[e.STORE_U8=59]="STORE_U8",e[e.STORE_U16=60]="STORE_U16",e[e.STORE_U32=61]="STORE_U32",e[e.STORE_U64=62]="STORE_U64",e[e.STORE_IMM_IND_U8=70]="STORE_IMM_IND_U8",e[e.STORE_IMM_IND_U16=71]="STORE_IMM_IND_U16",e[e.STORE_IMM_IND_U32=72]="STORE_IMM_IND_U32",e[e.STORE_IMM_IND_U64=73]="STORE_IMM_IND_U64",e[e.LOAD_IMM_JUMP=80]="LOAD_IMM_JUMP",e[e.BRANCH_EQ_IMM=81]="BRANCH_EQ_IMM",e[e.BRANCH_NE_IMM=82]="BRANCH_NE_IMM",e[e.BRANCH_LT_U_IMM=83]="BRANCH_LT_U_IMM",e[e.BRANCH_LE_U_IMM=84]="BRANCH_LE_U_IMM",e[e.BRANCH_GE_U_IMM=85]="BRANCH_GE_U_IMM",e[e.BRANCH_GT_U_IMM=86]="BRANCH_GT_U_IMM",e[e.BRANCH_LT_S_IMM=87]="BRANCH_LT_S_IMM",e[e.BRANCH_LE_S_IMM=88]="BRANCH_LE_S_IMM",e[e.BRANCH_GE_S_IMM=89]="BRANCH_GE_S_IMM",e[e.BRANCH_GT_S_IMM=90]="BRANCH_GT_S_IMM",e[e.MOVE_REG=100]="MOVE_REG",e[e.SBRK=101]="SBRK",e[e.COUNT_SET_BITS_64=102]="COUNT_SET_BITS_64",e[e.COUNT_SET_BITS_32=103]="COUNT_SET_BITS_32",e[e.LEADING_ZERO_BITS_64=104]="LEADING_ZERO_BITS_64",e[e.LEADING_ZERO_BITS_32=105]="LEADING_ZERO_BITS_32",e[e.TRAILING_ZERO_BITS_64=106]="TRAILING_ZERO_BITS_64",e[e.TRAILING_ZERO_BITS_32=107]="TRAILING_ZERO_BITS_32",e[e.SIGN_EXTEND_8=108]="SIGN_EXTEND_8",e[e.SIGN_EXTEND_16=109]="SIGN_EXTEND_16",e[e.ZERO_EXTEND_16=110]="ZERO_EXTEND_16",e[e.REVERSE_BYTES=111]="REVERSE_BYTES",e[e.STORE_IND_U8=120]="STORE_IND_U8",e[e.STORE_IND_U16=121]="STORE_IND_U16",e[e.STORE_IND_U32=122]="STORE_IND_U32",e[e.STORE_IND_U64=123]="STORE_IND_U64",e[e.LOAD_IND_U8=124]="LOAD_IND_U8",e[e.LOAD_IND_I8=125]="LOAD_IND_I8",e[e.LOAD_IND_U16=126]="LOAD_IND_U16",e[e.LOAD_IND_I16=127]="LOAD_IND_I16",e[e.LOAD_IND_U32=128]="LOAD_IND_U32",e[e.LOAD_IND_I32=129]="LOAD_IND_I32",e[e.LOAD_IND_U64=130]="LOAD_IND_U64",e[e.ADD_IMM_32=131]="ADD_IMM_32",e[e.AND_IMM=132]="AND_IMM",e[e.XOR_IMM=133]="XOR_IMM",e[e.OR_IMM=134]="OR_IMM",e[e.MUL_IMM_32=135]="MUL_IMM_32",e[e.SET_LT_U_IMM=136]="SET_LT_U_IMM",e[e.SET_LT_S_IMM=137]="SET_LT_S_IMM",e[e.SHLO_L_IMM_32=138]="SHLO_L_IMM_32",e[e.SHLO_R_IMM_32=139]="SHLO_R_IMM_32",e[e.SHAR_R_IMM_32=140]="SHAR_R_IMM_32",e[e.NEG_ADD_IMM_32=141]="NEG_ADD_IMM_32",e[e.SET_GT_U_IMM=142]="SET_GT_U_IMM",e[e.SET_GT_S_IMM=143]="SET_GT_S_IMM",e[e.SHLO_L_IMM_ALT_32=144]="SHLO_L_IMM_ALT_32",e[e.SHLO_R_IMM_ALT_32=145]="SHLO_R_IMM_ALT_32",e[e.SHAR_R_IMM_ALT_32=146]="SHAR_R_IMM_ALT_32",e[e.CMOV_IZ_IMM=147]="CMOV_IZ_IMM",e[e.CMOV_NZ_IMM=148]="CMOV_NZ_IMM",e[e.ADD_IMM_64=149]="ADD_IMM_64",e[e.MUL_IMM_64=150]="MUL_IMM_64",e[e.SHLO_L_IMM_64=151]="SHLO_L_IMM_64",e[e.SHLO_R_IMM_64=152]="SHLO_R_IMM_64",e[e.SHAR_R_IMM_64=153]="SHAR_R_IMM_64",e[e.NEG_ADD_IMM_64=154]="NEG_ADD_IMM_64",e[e.SHLO_L_IMM_ALT_64=155]="SHLO_L_IMM_ALT_64",e[e.SHLO_R_IMM_ALT_64=156]="SHLO_R_IMM_ALT_64",e[e.SHAR_R_IMM_ALT_64=157]="SHAR_R_IMM_ALT_64",e[e.ROT_R_64_IMM=158]="ROT_R_64_IMM",e[e.ROT_R_64_IMM_ALT=159]="ROT_R_64_IMM_ALT",e[e.ROT_R_32_IMM=160]="ROT_R_32_IMM",e[e.ROT_R_32_IMM_ALT=161]="ROT_R_32_IMM_ALT",e[e.BRANCH_EQ=170]="BRANCH_EQ",e[e.BRANCH_NE=171]="BRANCH_NE",e[e.BRANCH_LT_U=172]="BRANCH_LT_U",e[e.BRANCH_LT_S=173]="BRANCH_LT_S",e[e.BRANCH_GE_U=174]="BRANCH_GE_U",e[e.BRANCH_GE_S=175]="BRANCH_GE_S",e[e.LOAD_IMM_JUMP_IND=180]="LOAD_IMM_JUMP_IND",e[e.ADD_32=190]="ADD_32",e[e.SUB_32=191]="SUB_32",e[e.MUL_32=192]="MUL_32",e[e.DIV_U_32=193]="DIV_U_32",e[e.DIV_S_32=194]="DIV_S_32",e[e.REM_U_32=195]="REM_U_32",e[e.REM_S_32=196]="REM_S_32",e[e.SHLO_L_32=197]="SHLO_L_32",e[e.SHLO_R_32=198]="SHLO_R_32",e[e.SHAR_R_32=199]="SHAR_R_32",e[e.ADD_64=200]="ADD_64",e[e.SUB_64=201]="SUB_64",e[e.MUL_64=202]="MUL_64",e[e.DIV_U_64=203]="DIV_U_64",e[e.DIV_S_64=204]="DIV_S_64",e[e.REM_U_64=205]="REM_U_64",e[e.REM_S_64=206]="REM_S_64",e[e.SHLO_L_64=207]="SHLO_L_64",e[e.SHLO_R_64=208]="SHLO_R_64",e[e.SHAR_R_64=209]="SHAR_R_64",e[e.AND=210]="AND",e[e.XOR=211]="XOR",e[e.OR=212]="OR",e[e.MUL_UPPER_S_S=213]="MUL_UPPER_S_S",e[e.MUL_UPPER_U_U=214]="MUL_UPPER_U_U",e[e.MUL_UPPER_S_U=215]="MUL_UPPER_S_U",e[e.SET_LT_U=216]="SET_LT_U",e[e.SET_LT_S=217]="SET_LT_S",e[e.CMOV_IZ=218]="CMOV_IZ",e[e.CMOV_NZ=219]="CMOV_NZ",e[e.ROT_L_64=220]="ROT_L_64",e[e.ROT_L_32=221]="ROT_L_32",e[e.ROT_R_64=222]="ROT_R_64",e[e.ROT_R_32=223]="ROT_R_32",e[e.AND_INV=224]="AND_INV",e[e.OR_INV=225]="OR_INV",e[e.XNOR=226]="XNOR",e[e.MAX=227]="MAX",e[e.MAX_U=228]="MAX_U",e[e.MIN=229]="MIN",e[e.MIN_U=230]="MIN_U"}(ho||(ho={}));const uo=ho.MIN_U,go=(()=>{const e=new Array(uo+1);return e[ho.TRAP]=to.NO_ARGUMENTS,e[ho.FALLTHROUGH]=to.NO_ARGUMENTS,e[ho.ECALLI]=to.ONE_IMMEDIATE,e[ho.LOAD_IMM_64]=to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[ho.STORE_IMM_U8]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U16]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U32]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U64]=to.TWO_IMMEDIATES,e[ho.JUMP]=to.ONE_OFFSET,e[ho.JUMP_IND]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U64]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U64]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_IMM_IND_U8]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U16]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U32]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U64]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.LOAD_IMM_JUMP]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_EQ_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_NE_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LT_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LE_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GE_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GT_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LT_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LE_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GE_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GT_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.MOVE_REG]=to.TWO_REGISTERS,e[ho.SBRK]=to.TWO_REGISTERS,e[ho.COUNT_SET_BITS_64]=to.TWO_REGISTERS,e[ho.COUNT_SET_BITS_32]=to.TWO_REGISTERS,e[ho.LEADING_ZERO_BITS_64]=to.TWO_REGISTERS,e[ho.LEADING_ZERO_BITS_32]=to.TWO_REGISTERS,e[ho.TRAILING_ZERO_BITS_64]=to.TWO_REGISTERS,e[ho.TRAILING_ZERO_BITS_32]=to.TWO_REGISTERS,e[ho.SIGN_EXTEND_8]=to.TWO_REGISTERS,e[ho.SIGN_EXTEND_16]=to.TWO_REGISTERS,e[ho.ZERO_EXTEND_16]=to.TWO_REGISTERS,e[ho.REVERSE_BYTES]=to.TWO_REGISTERS,e[ho.STORE_IND_U8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ADD_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ADD_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.AND_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.XOR_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.OR_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.MUL_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.MUL_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_LT_U_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_LT_S_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.NEG_ADD_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.NEG_ADD_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_GT_U_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_GT_S_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.CMOV_IZ_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.CMOV_NZ_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_64_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_64_IMM_ALT]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_32_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_32_IMM_ALT]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.BRANCH_EQ]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_NE]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_LT_U]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_LT_S]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_GE_U]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_GE_S]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.LOAD_IMM_JUMP_IND]=to.TWO_REGISTERS_TWO_IMMEDIATES,e[ho.ADD_32]=to.THREE_REGISTERS,e[ho.ADD_64]=to.THREE_REGISTERS,e[ho.SUB_32]=to.THREE_REGISTERS,e[ho.SUB_64]=to.THREE_REGISTERS,e[ho.AND]=to.THREE_REGISTERS,e[ho.XOR]=to.THREE_REGISTERS,e[ho.OR]=to.THREE_REGISTERS,e[ho.MUL_32]=to.THREE_REGISTERS,e[ho.MUL_64]=to.THREE_REGISTERS,e[ho.MUL_UPPER_S_S]=to.THREE_REGISTERS,e[ho.MUL_UPPER_U_U]=to.THREE_REGISTERS,e[ho.MUL_UPPER_S_U]=to.THREE_REGISTERS,e[ho.DIV_U_32]=to.THREE_REGISTERS,e[ho.DIV_S_32]=to.THREE_REGISTERS,e[ho.REM_U_32]=to.THREE_REGISTERS,e[ho.REM_S_32]=to.THREE_REGISTERS,e[ho.DIV_U_64]=to.THREE_REGISTERS,e[ho.DIV_S_64]=to.THREE_REGISTERS,e[ho.REM_U_64]=to.THREE_REGISTERS,e[ho.REM_S_64]=to.THREE_REGISTERS,e[ho.SET_LT_U]=to.THREE_REGISTERS,e[ho.SET_LT_S]=to.THREE_REGISTERS,e[ho.SHLO_L_32]=to.THREE_REGISTERS,e[ho.SHLO_R_32]=to.THREE_REGISTERS,e[ho.SHAR_R_32]=to.THREE_REGISTERS,e[ho.SHLO_L_64]=to.THREE_REGISTERS,e[ho.SHLO_R_64]=to.THREE_REGISTERS,e[ho.SHAR_R_64]=to.THREE_REGISTERS,e[ho.CMOV_IZ]=to.THREE_REGISTERS,e[ho.CMOV_NZ]=to.THREE_REGISTERS,e[ho.ROT_L_64]=to.THREE_REGISTERS,e[ho.ROT_L_32]=to.THREE_REGISTERS,e[ho.ROT_R_64]=to.THREE_REGISTERS,e[ho.ROT_R_32]=to.THREE_REGISTERS,e[ho.AND_INV]=to.THREE_REGISTERS,e[ho.OR_INV]=to.THREE_REGISTERS,e[ho.XNOR]=to.THREE_REGISTERS,e[ho.MAX]=to.THREE_REGISTERS,e[ho.MAX_U]=to.THREE_REGISTERS,e[ho.MIN]=to.THREE_REGISTERS,e[ho.MIN_U]=to.THREE_REGISTERS,e})(),fo=e=>se(e),po=e=>ne(e),yo=e=>"number"==typeof e&&e<2**32?fo(e):po(e);function mo(e){return new bo(ne(e))}class bo{gas;constructor(e){this.gas=e}set(e){this.gas=ne(e)}get(){return yo(this.gas)}sub(e){const t=this.gas-ne(e);return t>=0n?(this.gas=ne(t),!1):(this.gas=ne(0n),!0)}}const Ao=[[ho.TRAP,1],[ho.FALLTHROUGH,1],[ho.ECALLI,1],[ho.LOAD_IMM_64,1],[ho.STORE_IMM_U8,1],[ho.STORE_IMM_U16,1],[ho.STORE_IMM_U32,1],[ho.STORE_IMM_U64,1],[ho.JUMP,1],[ho.JUMP_IND,1],[ho.LOAD_IMM,1],[ho.LOAD_U8,1],[ho.LOAD_I8,1],[ho.LOAD_U16,1],[ho.LOAD_I16,1],[ho.LOAD_U32,1],[ho.LOAD_I32,1],[ho.LOAD_U64,1],[ho.STORE_U8,1],[ho.STORE_U16,1],[ho.STORE_U32,1],[ho.STORE_U64,1],[ho.STORE_IMM_IND_U8,1],[ho.STORE_IMM_IND_U16,1],[ho.STORE_IMM_IND_U32,1],[ho.STORE_IMM_IND_U64,1],[ho.LOAD_IMM_JUMP,1],[ho.BRANCH_EQ_IMM,1],[ho.BRANCH_NE_IMM,1],[ho.BRANCH_LT_U_IMM,1],[ho.BRANCH_LE_U_IMM,1],[ho.BRANCH_GE_U_IMM,1],[ho.BRANCH_GT_U_IMM,1],[ho.BRANCH_LT_S_IMM,1],[ho.BRANCH_LE_S_IMM,1],[ho.BRANCH_GE_S_IMM,1],[ho.BRANCH_GT_S_IMM,1],[ho.MOVE_REG,1],[ho.SBRK,1],[ho.COUNT_SET_BITS_64,1],[ho.COUNT_SET_BITS_32,1],[ho.LEADING_ZERO_BITS_64,1],[ho.LEADING_ZERO_BITS_32,1],[ho.TRAILING_ZERO_BITS_64,1],[ho.TRAILING_ZERO_BITS_32,1],[ho.SIGN_EXTEND_8,1],[ho.SIGN_EXTEND_16,1],[ho.ZERO_EXTEND_16,1],[ho.REVERSE_BYTES,1],[ho.STORE_IND_U8,1],[ho.STORE_IND_U16,1],[ho.STORE_IND_U32,1],[ho.STORE_IND_U64,1],[ho.LOAD_IND_U8,1],[ho.LOAD_IND_I8,1],[ho.LOAD_IND_U16,1],[ho.LOAD_IND_I16,1],[ho.LOAD_IND_U32,1],[ho.LOAD_IND_I32,1],[ho.LOAD_IND_U64,1],[ho.ADD_IMM_32,1],[ho.AND_IMM,1],[ho.XOR_IMM,1],[ho.OR_IMM,1],[ho.MUL_IMM_32,1],[ho.SET_LT_U_IMM,1],[ho.SET_LT_S_IMM,1],[ho.SHLO_L_IMM_32,1],[ho.SHLO_R_IMM_32,1],[ho.SHAR_R_IMM_32,1],[ho.NEG_ADD_IMM_32,1],[ho.SET_GT_U_IMM,1],[ho.SET_GT_S_IMM,1],[ho.SHLO_L_IMM_ALT_32,1],[ho.SHLO_R_IMM_ALT_32,1],[ho.SHAR_R_IMM_ALT_32,1],[ho.CMOV_IZ_IMM,1],[ho.CMOV_NZ_IMM,1],[ho.ADD_IMM_64,1],[ho.MUL_IMM_64,1],[ho.SHLO_L_IMM_64,1],[ho.SHLO_R_IMM_64,1],[ho.SHAR_R_IMM_64,1],[ho.NEG_ADD_IMM_64,1],[ho.SHLO_L_IMM_ALT_64,1],[ho.SHLO_R_IMM_ALT_64,1],[ho.SHAR_R_IMM_ALT_64,1],[ho.ROT_R_64_IMM,1],[ho.ROT_R_64_IMM_ALT,1],[ho.ROT_R_32_IMM,1],[ho.ROT_R_32_IMM_ALT,1],[ho.BRANCH_EQ,1],[ho.BRANCH_NE,1],[ho.BRANCH_LT_U,1],[ho.BRANCH_LT_S,1],[ho.BRANCH_GE_U,1],[ho.BRANCH_GE_S,1],[ho.LOAD_IMM_JUMP_IND,1],[ho.ADD_32,1],[ho.SUB_32,1],[ho.MUL_32,1],[ho.DIV_U_32,1],[ho.DIV_S_32,1],[ho.REM_U_32,1],[ho.REM_S_32,1],[ho.SHLO_L_32,1],[ho.SHLO_R_32,1],[ho.SHAR_R_32,1],[ho.ADD_64,1],[ho.SUB_64,1],[ho.MUL_64,1],[ho.DIV_U_64,1],[ho.DIV_S_64,1],[ho.REM_U_64,1],[ho.REM_S_64,1],[ho.SHLO_L_64,1],[ho.SHLO_R_64,1],[ho.SHAR_R_64,1],[ho.AND,1],[ho.XOR,1],[ho.OR,1],[ho.MUL_UPPER_S_S,1],[ho.MUL_UPPER_U_U,1],[ho.MUL_UPPER_S_U,1],[ho.SET_LT_U,1],[ho.SET_LT_S,1],[ho.CMOV_IZ,1],[ho.CMOV_NZ,1],[ho.ROT_L_64,1],[ho.ROT_L_32,1],[ho.ROT_R_64,1],[ho.ROT_R_32,1],[ho.AND_INV,1],[ho.OR_INV,1],[ho.XNOR,1],[ho.MAX,1],[ho.MAX_U,1],[ho.MIN,1],[ho.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:fo(t)}])(t);return e[r]=s,e},{}),Io=(()=>{const e=new Array(uo+1);return e.fill(!1),e[ho.TRAP]=!0,e[ho.FALLTHROUGH]=!0,e[ho.JUMP]=!0,e[ho.JUMP_IND]=!0,e[ho.LOAD_IMM_JUMP]=!0,e[ho.LOAD_IMM_JUMP_IND]=!0,e[ho.BRANCH_EQ]=!0,e[ho.BRANCH_NE]=!0,e[ho.BRANCH_GE_U]=!0,e[ho.BRANCH_GE_S]=!0,e[ho.BRANCH_LT_U]=!0,e[ho.BRANCH_LT_S]=!0,e[ho.BRANCH_EQ_IMM]=!0,e[ho.BRANCH_NE_IMM]=!0,e[ho.BRANCH_LT_U_IMM]=!0,e[ho.BRANCH_LT_S_IMM]=!0,e[ho.BRANCH_LE_U_IMM]=!0,e[ho.BRANCH_LE_S_IMM]=!0,e[ho.BRANCH_GE_U_IMM]=!0,e[ho.BRANCH_GE_S_IMM]=!0,e[ho.BRANCH_GT_U_IMM]=!0,e[ho.BRANCH_GT_S_IMM]=!0,e})();class vo{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&Io[e[r]];for(let e=0;e<r;e++)t.isInstruction(e)&&s(e)&&this.basicBlocks.add(e+1+t.getNoOfBytesToNextInstruction(e+1))}isBeginningOfBasicBlock(e){return this.basicBlocks.has(e)}}const wo=(()=>{const e=new Array(uo+1);for(let t=0;t<uo+1;t++){const r=Ao[t]?.gas;e[t]=r}return e})();class So{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const Eo=e=>v(e,e>=0&&e<Gn,`Incorect page index: ${e}!`),Co=e=>v(e,e>=0&&e<=qn,`Incorrect page number: ${e}!`);function ko(e){return Co(e===qn?0:e+1)}function xo(e){return Gn*Math.ceil(e/Gn)}function Bo(e){return Co(e>>>12)}function _o(e){return Wn(e>>>12<<12)}function Ro(e){return Wn(e<<12>>>0)}class Oo{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=Ro(Co(e));return new Oo(r,t)}static fromMemoryIndex(e,t=!1){const r=_o(Wn(e%Fn));return new Oo(r,t)}}class Uo extends Error{constructor(){super("Out of bounds")}}Error,Error;class To extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class No extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class Do extends Error{constructor(){super("You are trying to access reserved memory!")}}class Mo extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class Po extends Error{constructor(){super("Out of memory")}}class Lo{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Wn((this.start+this.length)%Fn),t>0&&(this.lastIndex=Wn((this.end-1+Fn)%Fn))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Fn)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new Lo(e,t)}isEmpty(){return 0===this.length}isWrapped(){return this.start>=this.end&&!this.isEmpty()}isInRange(e){return this.isWrapped()?e>=this.start||e<this.end:e>=this.start&&e<this.end}overlapsWith(e){return null!==this.lastIndex&&null!==e.lastIndex&&(this.isInRange(e.start)||this.isInRange(e.lastIndex)||e.isInRange(this.start)||e.isInRange(this.lastIndex))}}const Ho=Lo.fromStartAndLength(Wn(0),65536);class Ko{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=Co((this.start+this.length)%zn)}static fromMemoryRange(e){const t=Bo(e.start);if(e.isEmpty())return new Ko(t,0);const r=Bo(e.lastIndex??e.end),s=ko(r);if((t===s||t===r)&&e.length>Gn)return new Ko(t,zn);const i=t<s?s-t:zn-t+s;return Ko.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>zn)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Ko(e,t)}isEmpty(){return 0===this.length}*[Symbol.iterator](){if(this.isEmpty())return;const e=this.end;let t=this.start;do{yield t,t=ko(t)}while(t!==e)}}class Vo{start;constructor(e){this.start=Ro(e)}}class Qo extends Vo{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Gn)return T.error(Oo.fromMemoryIndex(this.start+Gn));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),T.ok(_)}storeFrom(e,t){return T.error(Oo.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Fo extends Vo{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Gn,Math.max(r,jn));this.buffer=new ArrayBuffer(s,{maxByteLength:Gn}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Gn)return T.error(Oo.fromMemoryIndex(this.start+Gn));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),T.ok(_)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Gn){const r=Math.min(Gn,Math.max(jn,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),T.ok(_)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Gn){const r=Math.min(Gn,Math.max(jn,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Go;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Go||(Go={}));class $o{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new $o(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=Jn(Ho.end),t=Jn(Ho.end),r=Jn(Qn),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=Jn(Ho.end),this.virtualSbrkIndex=Jn(Ho.end),this.endHeapIndex=Jn(Qn),this.memory=new Map}copyFrom(e){this.sbrkIndex=e.sbrkIndex,this.virtualSbrkIndex=e.virtualSbrkIndex,this.endHeapIndex=e.endHeapIndex,this.memory=e.memory}storeFrom(e,t){if(0===t.length)return T.ok(_);const r=this.getPages(e,t.length,Go.WRITE);if(r.isError)return T.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=Eo(i%Gn),o=Math.min(Gn-s,n),a=i-e,c=t.subarray(a,a+o);r.storeFrom(s,c),i+=o,n-=o}return T.ok(_)}getPages(e,t,r){if(0===t)return T.ok([]);const s=Lo.fromStartAndLength(e,t),i=Ko.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return T.error(Oo.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return T.error(Oo.fromPageNumber(e));if(r===Go.WRITE&&!t.isWriteable())return T.error(Oo.fromPageNumber(e,!0));n.push(t)}return T.ok(n)}loadInto(e,t){if(0===e.length)return T.ok(_);const r=this.getPages(t,e.length,Go.READ);if(r.isError)return T.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=Eo(i%Gn),o=Math.min(Gn-s,n),a=i-t,c=e.subarray(a);r.loadInto(c,s,o),i+=o,n-=o}return T.ok(_)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(Qn<r+e||r+e>this.endHeapIndex)throw new Po;const s=Jn(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=Jn(xo(s)),n=Bo(t),o=(i-t)/Gn,a=Ko.fromStartAndLength(n,o);for(const e of a){const t=new Fo(e);this.memory.set(e,t)}return this.virtualSbrkIndex=s,this.sbrkIndex=i,r}getPageDump(e){const t=this.memory.get(e);return t?.getPageDump()??null}getDirtyPages(){return this.memory.keys()}}class jo{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new No}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(Ho))throw new Do}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),I(e<t,"end has to be bigger than start"),I(e%Gn===0,"start needs to be a multiple of page size (4096)"),I(t%Gn===0,"end needs to be a multiple of page size (4096)"),I(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ko.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Gn,(e+1)*Gn),i=new Qo(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),I(e<t,"end has to be bigger than start"),I(e%Gn===0,"start needs to be a multiple of page size (4096)"),I(t%Gn===0,"end needs to be a multiple of page size (4096)"),I(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ko.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Gn,(e+1)*Gn),i=new Fo(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Gn-e%Gn;I(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Bo(e),o=this.initialMemory.get(n);if(void 0===o)throw new Mo;const a=Eo(e-o.start);return o.setData(a,t),this}finalize(e,t){I(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=Lo.fromStartAndLength(e,t-e),s=Ko.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new To;const i=$o.fromInitialMemory({memory:this.initialMemory,sbrkIndex:Jn(e),endHeapIndex:t});return this.isFinalized=!0,i}}class qo{mathOps;shiftOps;bitOps;booleanOps;moveOps;bitRotationOps;constructor(e,t,r,s,i,n){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.bitRotationOps=n}dispatch(e,t){switch(e){case ho.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class zo{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,o,a){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=o,this.bitRotationOps=a}dispatch(e,t){switch(e){case ho.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class Wo{moveOps;memoryOps;bitOps;bitRotationOps;constructor(e,t,r,s){this.moveOps=e,this.memoryOps=t,this.bitOps=r,this.bitRotationOps=s}dispatch(e,t){switch(e){case ho.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class Jo{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case ho.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case ho.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class Yo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case ho.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class Xo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===ho.JUMP&&this.branchOps.jump(t.nextPc)}}class Zo{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case ho.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case ho.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class ea{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case ho.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class ta{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case ho.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class ra{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case ho.TRAP:this.noArgsOps.trap();break;case ho.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class sa{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case ho.LOAD_IMM_JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.secondImmediateDecoder,t.secondRegisterIndex);this.loadOps.loadImmediate(t.firstRegisterIndex,t.firstImmediateDecoder),this.dynamicJumpOps.jumpInd(e);break}}}}class ia{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===ho.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class na{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===ho.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class oa{regs;constructor(e){this.regs=e}or(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|this.regs.getU64(t))}orImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|t.getU64())}and(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&this.regs.getU64(t))}andImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&t.getU64())}xor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^this.regs.getU64(t))}xorImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^t.getU64())}andInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&~this.regs.getU64(t))}orInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|~this.regs.getU64(t))}xnor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^~this.regs.getU64(t))}countSetBits64(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1n&0x5555555555555555n,t=(0x3333333333333333n&t)+(t>>2n&0x3333333333333333n),t=t+(t>>4n)&0x0f0f0f0f0f0f0f0fn,t+=t>>8n,t+=t>>16n,t+=t>>32n,Number(0x7fn&t)}(this.regs.getU64(e)))}countSetBits32(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,63&t}(this.regs.getLowerU32(e)))}leadingZeroBits64(e,t){this.regs.setU32(t,function(e){const t=Number(e>>32n),r=Number(0xffffffffn&e),s=Math.clz32(t);return s<32?s:s+Math.clz32(r)}(this.regs.getU64(e)))}leadingZeroBits32(e,t){this.regs.setU32(t,Math.clz32(this.regs.getLowerU32(e)))}trailingZeroBits64(e,t){this.regs.setU32(t,function(e){if(0n===e)return 64;let t=e,r=0;for(;0n==(1n&t);)r++,t>>=1n;return r}(this.regs.getU64(e)))}trailingZeroBits32(e,t){this.regs.setU32(t,function(e){if(0===e)return 32;let t=e,r=0;for(;!(1&t);)r++,t>>>=1;return r}(this.regs.getLowerU32(e)))}signExtend(e,t){const r=2**t-1,s=e&r;return(s&1<<t-1)>0?~BigInt(r)|BigInt(s):BigInt(s)}signExtend8(e,t){const r=this.signExtend(this.regs.getLowerU32(e),8);this.regs.setU64(t,r)}signExtend16(e,t){const r=this.signExtend(this.regs.getLowerU32(e),16);this.regs.setU64(t,r)}zeroExtend16(e,t){const r=0x000000000000ffffn&this.regs.getU64(e);this.regs.setU64(t,r)}}const aa=4294967295,ca=-(2**31),la=32,ha=64n;function ua(e,t){return e>aa-t?aa-(aa-e+(aa-t))-1:e+t}function da(e,t){return(e+t)%2n**64n}function ga(e,t){return t>e?aa-t+e+1:e-t}function fa(e,t){return(2n**64n+e-t)%2n**64n}function pa(e,t){if(e>65536||t>65536){const r=65535&e,s=65535&t,i=r*s;return 65535&i|(i>>16)+(65535&r*(t>>16))+(65535&(e>>16)*s)<<16}return e*t}function ya(e,t){return e*t%2n**64n}function ma(e){return e>=1n<<63n?e-(1n<<64n):e}function ba(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function Aa(e,t){return ma(0xffffffffffffffffn&e*t>>64n)}function Ia(e,t){I(t>=0,"Shift count must be non-negative");const r=e<0?"1":"0",s=e.toString(2).padStart(64,r);return(e<0n?(1n<<BigInt(s.length))+e:e)>>t}function va(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function wa(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class Sa{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%la)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%ha)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%la)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,Ia(this.regs.getU64(e),this.regs.getU64(t)%ha))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%la)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%ha)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%la)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%ha)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%la)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,Ia(this.regs.getU64(e),t.getU64()%ha))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%la)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%ha)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%la)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%ha)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%la)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,Ia(t.getU64(),this.regs.getU64(e)%ha))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%la)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%ha)}}class Ea{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,no(ua(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,da(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,no(ua(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,da(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,no(pa(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,ba(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,Aa(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,ma(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,no(pa(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,Aa(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,ba(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,no(ga(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,fa(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,no(ga(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,fa(t.getU64(),this.regs.getU64(e)))}divSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===ca?this.regs.setU64(r,no(this.regs.getLowerU32(e))):this.regs.setI64(r,no(~~(this.regs.getLowerI32(e)/this.regs.getLowerI32(t))))}divSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setI64(r,~~(this.regs.getI64(e)/this.regs.getI64(t)))}divUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,no(~~(this.regs.getLowerU32(e)/this.regs.getLowerU32(t))))}divUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,~~(this.regs.getU64(e)/this.regs.getU64(t)))}remSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,BigInt(this.regs.getLowerI32(e))):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===ca?this.regs.setU64(r,0n):this.regs.setI64(r,no(this.regs.getLowerI32(e)%this.regs.getLowerI32(t)))}remSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,0n):this.regs.setI64(r,this.regs.getI64(e)%this.regs.getI64(t))}remUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,no(this.regs.getLowerU32(e))):this.regs.setU64(r,no(this.regs.getLowerU32(e)%this.regs.getLowerU32(t)))}remUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setU64(r,this.regs.getU64(e)%this.regs.getU64(t))}max(e,t,r){this.regs.setI64(r,va(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,va(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,wa(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,wa(this.regs.getU64(e),this.regs.getU64(t)))}}class Ca{regs;constructor(e){this.regs=e}setLessThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<t.getI64()?1n:0n)}setLessThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<t.getU64()?1n:0n)}setLessThanSigned(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<this.regs.getI64(t)?1n:0n)}setLessThanUnsigned(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<this.regs.getU64(t)?1n:0n)}setGreaterThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>t.getI64()?1n:0n)}setGreaterThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)>t.getU64()?1n:0n)}}class ka{regs;constructor(e){this.regs=e}cmovIfZeroImmediate(e,t,r){0n===this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfNotZeroImmediate(e,t,r){0n!==this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfZero(e,t,r){0n===this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}cmovIfNotZero(e,t,r){0n!==this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}moveRegister(e,t){this.regs.setU64(t,this.regs.getU64(e))}}var xa,Ba;(Ba=xa||(xa={}))[Ba.HALT=0]="HALT",Ba[Ba.PANIC=1]="PANIC",Ba[Ba.FAULT_ACCESS=2]="FAULT_ACCESS",Ba[Ba.FAULT=3]="FAULT",Ba[Ba.HOST=4]="HOST";class _a{regs;instructionResult;basicBlocks;constructor(e,t,r){this.regs=e,this.instructionResult=t,this.basicBlocks=r}setBasicBlocks(e){this.basicBlocks=e}branch(e,t){t&&(this.basicBlocks.isBeginningOfBasicBlock(e)?this.instructionResult.nextPc=e:this.instructionResult.status=xa.PANIC)}jump(e){this.branch(e,!0)}branchEqImmediate(e,t,r){this.branch(r,this.regs.getU64(e)===t.getU64())}branchEq(e,t,r){this.branch(r,this.regs.getU64(e)===this.regs.getU64(t))}branchNeImmediate(e,t,r){this.branch(r,this.regs.getU64(e)!==t.getU64())}branchNe(e,t,r){this.branch(r,this.regs.getU64(e)!==this.regs.getU64(t))}branchLtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<t.getU64())}branchLtUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)<this.regs.getU64(t))}branchLeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<=t.getU64())}branchGtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>t.getU64())}branchGeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>=t.getU64())}branchGeUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)>=this.regs.getU64(t))}branchLtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<t.getI64())}branchLtSigned(e,t,r){this.branch(r,this.regs.getI64(e)<this.regs.getI64(t))}branchLeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<=t.getI64())}branchGtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>t.getI64())}branchGeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>=t.getI64())}branchGeSigned(e,t,r){this.branch(r,this.regs.getI64(e)>=this.regs.getI64(t))}}class Ra{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}loadImmediate(e,t){this.regs.setU64(e,t.getU64())}loadImmediateU64(e,t){this.regs.setU64(e,t.getValue())}loadNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Wn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=e):s.fill(0,r)}loadSignedNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Wn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=e):(128&s[r-1])>0?s.fill(255,r):s.fill(0,r)}loadU8(e,t){this.loadNumber(e,t,1)}loadU16(e,t){this.loadNumber(e,t,2)}loadU32(e,t){this.loadNumber(e,t,4)}loadU64(e,t){this.loadNumber(e,t,8)}loadI8(e,t){this.loadSignedNumber(e,t,1)}loadI16(e,t){this.loadSignedNumber(e,t,2)}loadI32(e,t){this.loadSignedNumber(e,t,4)}loadIndU8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class Oa{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}storeU8(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,1))}storeU16(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,2))}storeU32(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,4))}storeU64(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,8))}storeIndU8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,8))}storeImmediateU8(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,1))}storeImmediateU16(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,2))}storeImmediateU32(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,4))}storeImmediateU64(e,t){this.store(e,t.getExtendedBytesAsLittleEndian())}storeImmediateIndU8(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Wn(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=_o(r.error.address)))}}class Ua{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=xa.PANIC}fallthrough(){}}class Ta{regs;jumpTable;instructionResult;basicBlocks;constructor(e,t,r,s){this.regs=e,this.jumpTable=t,this.instructionResult=r,this.basicBlocks=s}djump(e){if(4294901760===e)return void(this.instructionResult.status=xa.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=xa.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=xa.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=xa.PANIC}caluclateJumpAddress(e,t){return ua(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class Na{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=xa.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class Da{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}sbrk(e,t){try{this.regs.setU32(t,this.memory.sbrk(this.regs.getLowerU32(e)))}catch{this.instructionResult.status=xa.FAULT}}}class Ma{regs;constructor(e){this.regs=e}reverseBytes(e,t){const r=this.regs.getU64(e);let s=0n;for(let e=0;e<8;e++)s=s<<8n|r>>BigInt(8*e)&0xffn;this.regs.setU64(t,s)}rotate32Left(e,t){const r=t%32,s=2**32-1;return(e<<r&s|e>>>32-r)>>>0&s}rotate64Left(e,t){const r=t%64,s=(1n<<64n)-1n;return(e<<BigInt(r)&s|Ia(e,BigInt(64-r)))&s}rotate32Right(e,t){const r=t%32,s=2**32-1;return(e>>>r|e<<32-r&s)&s}rotate64Right(e,t){const r=t%64,s=(1n<<64n)-1n;return(Ia(e,BigInt(r))|e<<BigInt(64-r)&s)&s}rotR64Imm(e,t,r){const s=t.getU32(),i=this.regs.getU64(e);this.regs.setU64(r,this.rotate64Right(i,s))}rotR64ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU64();this.regs.setU64(r,this.rotate64Right(i,s))}rotR32Imm(e,t,r){const s=t.getU32(),i=this.regs.getLowerU32(e);this.regs.setU32(r,this.rotate32Right(i,s))}rotR32ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU32();this.regs.setU32(r,this.rotate32Right(i,s))}rotL64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Left(s,i))}rotL32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Left(s,i))}rotR64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Right(s,i))}rotR32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Right(s,i))}}class Pa{indices;constructor(e,t){I(0===e||t.length%e===0,`Length of jump table (${t.length}) should be a multiple of item lenght (${e})!`);const r=0===e?0:t.length/e;this.indices=new Uint32Array(r);for(let s=0;s<r;s++)this.indices[s]=this.decodeNext(t.subarray(s*e,(s+1)*e))}decodeNext(e){const t=e.length;let r=0;for(let s=0;s<t;s++){if((4278190080&r)>0)return 2**32-1;r<<=8,r|=e[t-s-1]}return r}hasIndex(e){return e<this.indices.length&&e>=0}getDestination(e){return this.indices[e]}static empty(){return new Pa(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const La=Js.new(void 0,"pvm-interpreter");var Ha;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(Ha||(Ha={}));class Ka{code;mask;jumpTable;constructor(e){const{code:t,mask:r,jumpTable:s,jumpTableItemLength:i}=this.decodeProgram(e);this.code=new Uint8Array(t),this.mask=new ro(r),this.jumpTable=new Pa(i,s)}decodeProgram(e){const t=ue.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,o=t.bytes(n).raw,a=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:a,jumpTableItemLength:s,jumpTable:o}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return T.ok(new Ka(e))}catch(e){return La.error(`Invalid program: ${e}`),T.error(Ha.InvalidProgramError)}}}class Va{useSbrkGas;ignoreInstructionGas;registers=new io;code=new Uint8Array;mask=ro.empty();pc=0;gas=mo(yo(0));initialGas=mo(yo(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new So;memory=new $o;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=Yn.OK;argsDecodingResults=(()=>{const e=new Array(lo);return e[to.NO_ARGUMENTS]={type:to.NO_ARGUMENTS,noOfBytesToSkip:1},e[to.ONE_IMMEDIATE]={type:to.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new so},e[to.TWO_REGISTERS]={type:to.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[to.THREE_REGISTERS]={type:to.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new so,nextPc:0},e[to.TWO_REGISTERS_ONE_OFFSET]={type:to.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[to.TWO_REGISTERS_ONE_IMMEDIATE]={type:to.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new so},e[to.ONE_REGISTER_ONE_IMMEDIATE]={type:to.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new so},e[to.ONE_REGISTER_TWO_IMMEDIATES]={type:to.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new so,secondImmediateDecoder:new so},e[to.ONE_OFFSET]={type:to.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[to.TWO_IMMEDIATES]={type:to.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new so,secondImmediateDecoder:new so},e[to.TWO_REGISTERS_TWO_IMMEDIATES]={type:to.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new so,secondImmediateDecoder:new so,firstRegisterIndex:0,secondRegisterIndex:0},e[to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new co},e})();basicBlocks;jumpTable=Pa.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new ao,this.basicBlocks=new vo;const r=new Ea(this.registers),s=new Sa(this.registers),i=new oa(this.registers),n=new Ca(this.registers),o=new ka(this.registers),a=new _a(this.registers,this.instructionResult,this.basicBlocks),c=new Ra(this.registers,this.memory,this.instructionResult),l=new Oa(this.registers,this.memory,this.instructionResult),h=new Ua(this.instructionResult),u=new Ta(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),d=new Na(this.instructionResult),g=new Da(this.registers,this.memory,this.instructionResult),f=new Ma(this.registers);this.threeRegsDispatcher=new qo(r,s,i,n,o,f),this.twoRegsOneImmDispatcher=new zo(r,s,i,n,o,l,c,f),this.twoRegsDispatcher=new Wo(o,g,i,f),this.oneRegOneImmOneOffsetDispatcher=new Jo(a,c),this.twoRegsOneOffsetDispatcher=new Yo(a),this.oneOffsetDispatcher=new Xo(a),this.oneRegOneImmDispatcher=new Zo(c,l,u),this.twoImmsDispatcher=new ta(l),this.oneRegTwoImmsDispatcher=new ea(l),this.noArgsDispatcher=new ra(h),this.twoRegsTwoImmsDispatcher=new sa(c,u),this.oneImmDispatcher=new ia(d),this.oneRegOneExtImmDispatcher=new na(c)}reset(e,t,r,s,i){const n=new Ka(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=mo(r),this.initialGas=mo(r),this.status=Yn.OK,this.argsDecoder.reset(this.code,this.mask),this.basicBlocks.reset(this.code,this.mask),this.instructionResult.reset(),void 0!==s?this.registers.copyFrom(s):this.registers.reset(),void 0!==i?this.memory.copyFrom(i):this.memory.reset()}printProgram(){const e=(t=this.code,r=this.mask,t.reduce((e,t,s)=>(r.isInstruction(s)?e.push([ho[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===Yn.OK;);}nextStep(){this.status===Yn.HOST&&(this.status=Yn.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??ho.TRAP,t=void 0!==ho[e],r=wo[e]??wo[ho.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=Yn.OOG,this.status;const s=go[e]??to.NO_ARGUMENTS,i=this.argsDecodingResults[s];if(this.argsDecoder.fillArgs(this.pc,i),t)switch(this.instructionResult.nextPc=this.pc+i.noOfBytesToSkip,i.type){case to.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case to.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS:if(this.useSbrkGas&&e===ho.SBRK){const e=e=>xo(e)/Gn*16;if(this.gas.sub(yo(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=Yn.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case to.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case to.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case to.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=xa.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==xa.FAULT&&this.instructionResult.status!==xa.FAULT_ACCESS||this.gas.sub(wo[ho.TRAP]),this.instructionResult.status){case xa.FAULT:this.status=Yn.FAULT;break;case xa.HALT:this.status=Yn.HALT;break;case xa.PANIC:case xa.FAULT_ACCESS:this.status=Yn.PANIC;break;case xa.HOST:this.status=Yn.HOST}return this.status}return this.pc=this.instructionResult.nextPc,this.status}getRegisters(){return this.registers}getPC(){return this.pc}setNextPC(e){this.pc=e}getGas(){return this.gas.get()}getGasConsumed(){const e=po(this.initialGas.get())-po(this.gas.get());return e<0?this.initialGas.get():po(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?se(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(Co(e))}}class Qa{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?T.ok(_):e+ne(t.length)>Fn?T.error(new Uo):this.memory.storeFrom(Wn(Number(e)),t)}loadInto(e,t){return 0===e.length?T.ok(_):t+ne(e.length)>Fn?T.error(new Uo):this.memory.loadInto(e,Wn(Number(t)))}getMemory(){return this.memory}}class Fa{registers;constructor(e){this.registers=e}get(e){return ne(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class Ga{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,I(null===t&&null!==r||null!==t&&null===r,"`status` and `memorySlice` must not both be null or both be non-null — exactly one must be provided")}static fromStatus(e,t){return new Ga(e,t,null)}static fromMemorySlice(e,t){return new Ga(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class $a{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===Yn.OOG)return Ga.fromStatus(r,e);if(e===Yn.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),o=new Uint8Array(n),a=Wn(i);return e.loadInto(o,a).isError?Ga.fromMemorySlice(r,new Uint8Array):Ga.fromMemorySlice(r,o)}return Ga.fromStatus(r,Yn.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==Yn.HOST)return this.getReturnValue(t,e);I(null!==e.getExitParam(),"We know that the exit param is not null, because the status is `Status.HOST`");const r=e.getExitParam()??-1,s=e.getGasCounter(),i=new Fa(e.getRegisters()),n=new Qa(e.getMemory()),o=this.hostCalls.get(Zn(r)),a="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(a))return Ga.fromStatus(e.getGasConsumed(),Yn.OOG);if(await o.execute(s,i,n)===eo.Halt)return t=Yn.HALT,this.getReturnValue(t,e);e.runProgram(),t=e.getStatus()}}async runProgram(e,t,r,s,i){const n=await this.pvmInstanceManager.getInstance();n.reset(e,t,r,s,i);try{return await this.execute(n)}finally{this.pvmInstanceManager.releaseInstance(n)}}}class ja{instances=[];waitingQueue=[];constructor(e){for(let t=0;t<e;t++)this.instances.push(new Va({useSbrkGas:!1,ignoreInstructionGas:!0}))}async getInstance(){const e=this.instances.pop();return void 0!==e?Promise.resolve(e):new Promise(e=>{this.waitingQueue.push(e)})}releaseInstance(e){const t=this.waitingQueue.shift();if(void 0!==t)return t(e);this.instances.push(e)}}const qa={NONE:ne(0xffffffffffffffffn),WHAT:ne(0xfffffffffffffffen),OOB:ne(0xfffffffffffffffdn),WHO:ne(0xfffffffffffffffcn),FULL:ne(0xfffffffffffffffbn),CORE:ne(0xfffffffffffffffan),CASH:ne(0xfffffffffffffff9n),LOW:ne(0xfffffffffffffff8n),HUH:ne(0xfffffffffffffff7n),OK:ne(0n)},za=se(2**32-1),Wa=ne(za),Ja=vr(2**32-1);function Ya(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:Xa(s)}function Xa(e){const{lower:t,upper:r}=(e=>{const t=e>>32n;return{lower:Number(e&2n**32n-1n),upper:Number(t)}})(e);return 0===r?vr(t):null}function Za(e,t){I(t.length>=4,"Not enough space in the destination."),t.set(ce(e))}function ec(e){return e>Wa?za:se(Number(e))}const tc=Js.new(void 0,"host-calls");class rc{hostCalls=new Map;missing=new sc;constructor(...e){for(const t of e)I(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){const t=this.hostCalls.get(e)??this.missing;return tc.trace(`[${t.currentServiceId}] PVM invoking ${e} (${t.constructor.name}:${t.index})`),t}}class sc{index=Zn(2**32-1);gasCost=fo(10);currentServiceId=Ja;execute(e,t,r){return t.set(7,qa.WHAT),Promise.resolve(void 0)}}const ic=4096,nc=65536,oc=2**24,ac=4278059008,cc=4278124544;function lc(e){return ic*Math.ceil(e/ic)}class hc extends k{start;end;data;static from({start:e,end:t,data:r}){return new hc(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class uc extends k{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class dc extends k{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function gc(e,t,r=null){return new hc(e,t,r)}class fc{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?pc(e):{code:e},{code:n,memory:o,registers:a}=function(e,t){const r=ue.fromBlob(e),s=r.u24(),i=r.u24(),n=v(t.length,t.length<=oc,"Incorrect arguments length"),o=v(s,s<=oc,"Incorrect readonly segment length"),a=v(i,i<=oc,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),h=r.bytes(o).raw,u=r.bytes(a).raw,d=r.u32(),g=r.bytes(d).raw;r.finish();const f=nc+lc(o),p=131072+(y=o,nc*Math.ceil(y/nc));var y;const m=p+lc(a),b=p+lc(a)+c*ic,A=ac-lc(l),I=ac,w=cc,S=w+lc(n),E=S+lc(n);function C(e){return!1!==e}const k=[o>0&&gc(65536,f,h),n>0&&gc(w,S,t),S<E&&gc(S,E)].filter(C),x=[a>0&&gc(p,m,u),m<b&&gc(m,b),A<I&&gc(A,I)].filter(C);return new dc(g,new uc(k,x,b,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(ac),t[7]=BigInt(cc),t[8]=BigInt(e),t}(t.length))}(s,t),c=new io;c.copyFrom(a);const l=new jo;for(const{start:e,end:t,data:r}of o.readable){const s=Wn(e),i=Wn(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of o.writeable){const s=Wn(e),i=Wn(t);l.setWriteablePages(s,i,r??new Uint8Array)}const h=Wn(o.sbrkIndex),u=Jn(o.heapEnd),d=l.finalize(h,u);return new fc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?pc(e):{code:e},i=new io,n=new $o;return new fc(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function pc(e){const t=ue.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var yc,mc,bc;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(yc||(yc={}));class Ac{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return ut(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return ut(this.keccakHasher,[e,t,r])}header(e){return new Me(Ge(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=Ge(e.report.encoded(),this.allocator).asOpaque();return D.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=me.encodeObject(ke.sequenceVarLen(zi),t,this.context),s=Ge(e.tickets.encoded(),this.allocator).asOpaque(),i=Ge(e.preimages.encoded(),this.allocator).asOpaque(),n=Ge(r,this.allocator).asOpaque(),o=Ge(e.assurances.encoded(),this.allocator).asOpaque(),a=Ge(e.disputes.encoded(),this.allocator).asOpaque(),c=D.blobFromParts([s.raw,i.raw,n.raw,o.raw,a.raw]);return new Pe(Ge(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Mr.Codec,e)}encode(e,t){const r=me.encodeObject(e,t,this.context);return new Pe(Ge(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(mc||(mc={}));class Ic{state;constructor(e){this.state=e}integrate(e){for(let t=1;t<e.preimages.length;t++){const r=e.preimages[t-1],s=e.preimages[t];if(!(r.requester<s.requester)&&(r.requester>s.requester||s.blob.compare(r.blob).isLessOrEqual()))return T.error(mc.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=Ge(i).asOpaque(),o=this.state.getService(t);if(null===o)return T.error(mc.AccountNotFound);const a=o.hasPreimage(n),c=o.getLookupHistory(n,se(i.length));if(a||null===c||!Ci.isRequested(c))return T.error(mc.PreimageUnneeded);s.push(_i.provide({serviceId:t,preimage:wi.create({hash:n,blob:i}),slot:r}))}return T.ok({preimages:s})}}class vc{spec;importer;toImport=yt.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?d.Greater:r>0?d.Less:d.Equal});lastEpoch=Er(2**32-1);constructor(e,t){this.spec=e,this.importer=t}tryToReadTimeSlot(e){try{return e.header.view().timeSlotIndex.materialize()}catch{return null}}isCurrentEpoch(e){const t=Math.floor(e/this.spec.epochLength);return this.lastEpoch===t}startPreverification(){for(const e of this.toImport)this.isCurrentEpoch(e.timeSlot)&&(e.seal=this.importer.preverifySeal(e.timeSlot,e.block))}push(e){const t=this.tryToReadTimeSlot(e);if(null===t)return null;const r={timeSlot:t,block:e,seal:this.isCurrentEpoch(t)?this.importer.preverifySeal(t,e):Promise.resolve(null)};return this.toImport.insert(r),t}shift(){const e=this.toImport.pop();if(void 0!==e){const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=Er(t),r&&this.startPreverification()}return e}}!function(e){e[e.ParentNotFound=0]="ParentNotFound",e[e.InvalidTimeSlot=1]="InvalidTimeSlot",e[e.InvalidExtrinsic=2]="InvalidExtrinsic",e[e.StateRootNotFound=3]="StateRootNotFound",e[e.InvalidStateRoot=4]="InvalidStateRoot",e[e.AlreadyImported=5]="AlreadyImported"}(bc||(bc={}));const wc=M.zero(Ne).asOpaque();class Sc{hasher;blocks;constructor(e,t){this.hasher=e,this.blocks=t}async verifyBlock(e){const t=e.header.view(),r=this.hasher.header(t);if(null!==this.blocks.getHeader(r.hash))return T.error(bc.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(wc)){const e=this.blocks.getHeader(s);if(null===e)return T.error(bc.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return T.error(bc.InvalidTimeSlot,`Invalid time slot index: ${r}, expected > ${i}`)}const i=t.extrinsicHash.materialize(),n=this.hasher.extrinsic(e.extrinsic.view());if(!i.isEqualTo(n.hash))return T.error(bc.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const o=t.priorStateRoot.materialize(),a=this.blocks.getPostStateRoot(s);return null===a?T.error(bc.StateRootNotFound,`Posterior state root ${s.toString()} not found`):o.isEqualTo(a)?T.ok(r.hash):T.error(bc.InvalidStateRoot,`Invalid prior state root: ${o.toString()}, expected ${a.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var Ec;function Cc(e,t){for(let r=1;r<e.length;r++)if(e[r-1][t].compare(e[r][t]).isGreaterOrEqual())return!1;return!0}!function(e){e.AlreadyJudged="already_judged",e.BadVoteSplit="bad_vote_split",e.VerdictsNotSortedUnique="verdicts_not_sorted_unique",e.JudgementsNotSortedUnique="judgements_not_sorted_unique",e.CulpritsNotSortedUnique="culprits_not_sorted_unique",e.FaultsNotSortedUnique="faults_not_sorted_unique",e.NotEnoughCulprits="not_enough_culprits",e.NotEnoughFaults="not_enough_faults",e.CulpritsVerdictNotBad="culprits_verdict_not_bad",e.FaultVerdictWrong="fault_verdict_wrong",e.OffenderAlreadyReported="offender_already_reported",e.BadJudgementAge="bad_judgement_age",e.BadValidatorIndex="bad_validator_index",e.BadSignature="bad_signature",e.BadGuarantorKey="bad_guarantor_key",e.BadAuditorKey="bad_auditor_key"}(Ec||(Ec={}));const kc=D.blobFromString("jam_valid").raw,xc=D.blobFromString("jam_invalid").raw,Bc=D.blobFromString("jam_guarantee").raw;function _c({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:D.blobFromParts(Bc,r.raw)}}function Rc({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?kc:xc;return{key:s,signature:r,message:D.blobFromParts(i,e.raw)}}function Oc(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?kc:xc;return{key:r,signature:i,message:D.blobFromParts(n,t.raw)}}class Uc{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!Cc(e.culprits,"key"))return T.error(Ec.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return T.error(Ec.OffenderAlreadyReported);if(!s.has(i))return T.error(Ec.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(o))return T.error(Ec.CulpritsVerdictNotBad);const a=r.culprits[n];if(!a?.isValid)return T.error(Ec.BadSignature)}return T.ok(null)}verifyFaults(e,t,r,s){if(!Cc(e.faults,"key"))return T.error(Ec.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o,wasConsideredValid:a}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return T.error(Ec.OffenderAlreadyReported);if(!s.has(i))return T.error(Ec.BadAuditorKey);if(a){const e=t.toAddToGoodSet.findExact(o),r=t.toAddToBadSet.findExact(o);if(void 0!==e||void 0===r)return T.error(Ec.FaultVerdictWrong)}if(!r.faults[n].isValid)return T.error(Ec.BadSignature)}return T.ok(null)}verifyVerdicts(e,t){if(!Cc(e.verdicts,"workReportHash"))return T.error(Ec.VerdictsNotSortedUnique);if(e.verdicts.some(e=>!function(e){for(let t=1;t<e.length;t++)if(e[t-1].index>=e[t].index)return!1;return!0}(e.votes)))return T.error(Ec.JudgementsNotSortedUnique);const r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);let s=0;for(const{votesEpoch:i,votes:n}of e.verdicts){if(i!==r&&i+1!==r)return T.error(Ec.BadJudgementAge);const e=i===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const{index:r}of n){const i=e[r]?.ed25519;if(void 0===i)return T.error(Ec.BadValidatorIndex);if(!t.judgements[s].isValid)return T.error(Ec.BadSignature);s+=1}}return T.ok(null)}verifyIfAlreadyJudged(e){for(const t of e.verdicts){const e=this.state.disputesRecords.goodSet.findExact(t.workReportHash),r=this.state.disputesRecords.badSet.findExact(t.workReportHash),s=this.state.disputesRecords.wonkySet.findExact(t.workReportHash);if(void 0!==e||void 0!==r||void 0!==s)return T.error(Ec.AlreadyJudged)}return T.ok(null)}calculateVotesForWorkReports(e){const t=dt.new();for(const r of e.verdicts){const e=r.votes,s=r.workReportHash;let i=0;for(const{isWorkReportValid:t}of e)t&&(i+=1);t.set(s,i)}return t}verifyVotesForWorkReports(e,t){for(const[r,s]of e)if(s===this.chainSpec.validatorsSuperMajority){const e=t.faults.find(e=>e.workReportHash.isEqualTo(r));if(void 0===e)return T.error(Ec.NotEnoughFaults)}else if(0===s){const e=t.culprits.find(e=>e.workReportHash.isEqualTo(r)),s=t.culprits.findLast(e=>e.workReportHash.isEqualTo(r));if(e===s)return T.error(Ec.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return T.error(Ec.BadVoteSplit);return T.ok(null)}getDisputesRecordsNewItems(e){const t=[],r=[],s=[];for(const[i,n]of e)n>=this.chainSpec.validatorsSuperMajority?t.push(i):0===n?r.push(i):n>=this.chainSpec.thirdOfValidators&&s.push(i);return{toAddToGoodSet:mt.fromArray(di,t),toAddToBadSet:mt.fromArray(di,r),toAddToWonkySet:mt.fromArray(di,s)}}getClearedCoreAssignment(e){const t=this.state.availabilityAssignment.slice();for(let r=0;r<t.length;r++){const s=t[r];if(null!==s){const i=e.get(s.workReport.hash);void 0!==i&&i<this.chainSpec.validatorsSuperMajority&&(t[r]=null)}}return ai(t,this.chainSpec)}getOffenders(e){const t=[];for(const{key:r}of e.culprits)t.push(r);for(const{key:r}of e.faults)t.push(r);return t}getUpdatedDisputesRecords(e,t){const r=yt.fromArray(di,t);return ui.create({goodSet:mt.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:mt.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:mt.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:mt.fromTwoSortedCollections(this.state.disputesRecords.punishSet,r)})}prepareSignaturesToVerification(e){const t={culprits:[],judgements:[],faults:[]},r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);for(const{votesEpoch:s,votes:i,workReportHash:n}of e.verdicts){const e=s===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const r of i){const s=e[r.index];if(void 0===s)return T.error(Ec.BadValidatorIndex);const i=s.ed25519;t.judgements.push(Oc(r,n,i))}}return t.culprits=e.culprits.map(_c),t.faults=e.faults.map(Rc),T.ok(t)}getValidatorKeys(){const e=this.state.disputesRecords.punishSet,t=this.state.currentValidatorData.map(e=>e.ed25519),r=this.state.previousValidatorData.map(e=>e.ed25519),s=t.concat(r).filter(t=>!e.has(t));return gt.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return T.error(t.error);const r=async function(e){const t={culprits:[],faults:[],judgements:[]},r=Object.entries(e);for(const[e,s]of r)t[e]=(await hr(s)).map((e,t)=>({isValid:e,signature:s[t].signature}));return Promise.resolve(t)}(t.ok),s=this.calculateVotesForWorkReports(e),i=this.getDisputesRecordsNewItems(s),n=await r,o=this.getValidatorKeys(),a=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,o),this.verifyFaults(e,i,n,o),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(a?.isError)return T.error(a.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),h=this.getClearedCoreAssignment(s);return T.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:h}})}}const Tc=D.blobFromString("jam_entropy").raw,Nc=D.blobFromString("jam_fallback_seal").raw,Dc=D.blobFromString("jam_ticket_seal").raw;var Mc;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(Mc||(Mc={}));const Pc=async function(e,t,r,s,i,n){const o=D.blobFromParts(t.map(e=>e.raw)).raw,a=await e.verifySeal(o,r,s.raw,i.raw,n.raw);return a[0]===Mc.Error?T.error(null):T.ok(M.fromBlob(a.subarray(1),Ne).asOpaque())},Lc=async function(e,t,r,s){const i=s.length+Dc.length+1,n=D.blobFromParts(r.map(e=>D.blobFromParts([e.signature.raw,Dc,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,o=D.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(o,n,i);return Array.from(D.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===Mc.Ok,entropyHash:M.fromBlob(e.raw.subarray(1,33),Ne).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:M.zero(Ne).asOpaque()}));throw e}},Hc=async function(e,t){const r=D.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===Mc.Error?T.error(null):T.ok(M.fromBlob(s.subarray(1),Ue).asOpaque())};class Kc{runInternal;state;static new(e,t){return new Kc(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===Ys.parentPort)throw new Error("This method is meant to be run inside a worker thread!");Ys.parentPort.once("close",()=>{process.exit(0)}),Ys.parentPort.once("message",e=>{this.listenTo(e),Ys.parentPort?.postMessage("ready")})}listenTo(e){e.once("close",()=>{e.removeAllListeners(),process.exit(0)}),e.on("message",t=>{const{params:r}=t;this.run(r).then(t=>{const r=T.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=T.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class Vc{workers;maxWorkers;workerPath;static async initialize(e,t){I(t.maxWorkers>0,"Max workers has to be positive."),I(t.minWorkers<=t.maxWorkers,"Min workers has to be lower or equal to max workers.");const r=[];for(let s=0;s<t.minWorkers;s++)r.push(await Qc(e));return new Vc(r,t.maxWorkers,e)}freeWorkerIndices=[];taskQueue=[];isDestroyed=!1;isWorkerInitializing=!1;constructor(e,t,r){this.workers=e,this.maxWorkers=t,this.workerPath=r;for(let t=0;t<e.length;t++)this.freeWorkerIndices.push(t)}async initNewWorker(e=()=>{}){this.workers.length>=this.maxWorkers?console.warn(`Task queue has ${this.taskQueue.length} pending items and we can't init any more workers.`):this.isWorkerInitializing||(this.isWorkerInitializing=!0,this.workers.push(await Qc(this.workerPath)),this.freeWorkerIndices.push(this.workers.length-1),this.isWorkerInitializing=!1,e())}async destroy(){for(const e of this.workers)e.port.close(),await e.worker.terminate();this.workers.length=0,this.isDestroyed=!0}async run(e){return new Promise((t,r)=>{this.isDestroyed?r("pool destroyed"):(this.taskQueue.push({params:e,resolve:t,reject:r}),this.processEntryFromTaskQueue())})}processEntryFromTaskQueue(){const e=this.freeWorkerIndices.pop();if(void 0===e)return void(this.taskQueue.length>5&&this.initNewWorker(()=>{this.processEntryFromTaskQueue()}));const t=this.taskQueue.pop();void 0!==t?this.workers[e].runTask(t,()=>{this.freeWorkerIndices.push(e),this.processEntryFromTaskQueue()}):this.freeWorkerIndices.push(e)}}async function Qc(e){const{port1:t,port2:r}=new MessageChannel,s=new Ys.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new Fc(s,r)}class Fc{worker;port;constructor(e,t){this.worker=e,this.port=t}runTask(e,t){const r={params:e.params};this.port.once("message",r=>{r.isOk?e.resolve(r.ok):e.reject(new Error(r.error)),t()}),this.port.postMessage(r,r.params.getTransferList())}}var Gc;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(Gc||(Gc={}));class $c{data;constructor(e){this.data=e}getTransferList(){return[]}}class jc{params;constructor(e){this.params=e}getTransferList(){return[]}}const qc=Kc.new(e=>{const t=e.params,r=t.method;return r===Gc.RingCommitment?Promise.resolve(new $c((0,Re.hc)(t.keys))):r===Gc.BatchVerifyTickets?Promise.resolve(new $c((0,Re.ZJ)(t.keys,t.ticketsData,t.contextLength))):r===Gc.VerifySeal?Promise.resolve(new $c((0,Re.KG)(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void w(r)},null);class zc{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=Ns().cpus().length;return new zc(e?qc:await Vc.initialize(new URL(o(884),o.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new jc({method:Gc.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new jc({method:Gc.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new jc({method:Gc.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const Wc=(e,t)=>q(e.id,t.id);var Jc,Yc,Xc,Zc,el,tl,rl;!function(e){e[e.IncorrectData=1]="IncorrectData",e[e.BadSlot=2]="BadSlot",e[e.UnexpectedTicket=3]="UnexpectedTicket",e[e.BadTicketOrder=4]="BadTicketOrder",e[e.BadTicketProof=5]="BadTicketProof",e[e.BadTicketAttempt=6]="BadTicketAttempt",e[e.DuplicateTicket=7]="DuplicateTicket"}(Jc||(Jc={}));class sl{chainSpec;state;bandersnatch;constructor(e,t,r=zc.new({synchronous:!0})){this.chainSpec=e,this.state=t,this.bandersnatch=r}isEpochChanged(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)>t}isSameEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t}isNextEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t+1}getSlotPhaseIndex(e){return e%this.chainSpec.epochLength}getEntropy(e,t){const[r,...s]=this.state.entropy,i=Fe([r.raw,t]).asOpaque();return this.isEpochChanged(e)?pt.new([i,r,s[0],s[1]],4):pt.new([i,...s],4)}async getValidatorKeys(e,t){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return T.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?yi.create({bandersnatch:M.zero(Oe).asOpaque(),ed25519:M.zero(cr).asOpaque(),bls:M.zero(Te).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await Hc(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?T.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):T.error(Jc.IncorrectData)}outsideInSequencer(e){const t=e.length,r=new Array(t),s=Math.floor(t/2);for(let i=0;i<s;i+=1)r[2*i]=e[i],r[2*i+1]=e[t-i-1];return 2*s<t&&(r[2*s]=e[s]),xr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=se(0);n<r;n++){const r=ce(n),o=Fe([e.raw,r]).raw,a=ue.fromBlob(o).u32()%i;s.push(t[a].bandersnatch)}return xr(s,this.chainSpec)}getSlotKeySequence(e,t,r){const s=this.getSlotPhaseIndex(this.state.timeslot);return this.isNextEpoch(e)&&s>=this.chainSpec.contestLength&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?Ai.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:Ai.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return Jr.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>Wr.create(e))})}verifyTickets(e){const t=e.length;for(let r=1;r<t;r++){const t=e[r-1].id.compare(e[r].id);if(t.isEqual())return T.error(Jc.DuplicateTicket);if(t.isGreater())return T.error(Jc.BadTicketOrder)}return T.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await Lc(await this.bandersnatch,r.map(e=>e.bandersnatch),t,s),n=t.map((e,t)=>({id:i[t].entropyHash,attempt:e.attempt}));if(!i.every(e=>e.isValid))return T.error(Jc.BadTicketProof);const o=this.verifyTickets(n);if(o.isError)return T.error(o.error);if(this.isEpochChanged(e))return T.ok(n);const a=mt.fromSortedArray(Wc,this.state.ticketsAccumulator),c=mt.fromSortedArray(Wc,n),l=mt.fromTwoSortedCollections(a,c);return a.length+c.length!==l.length?T.error(Jc.DuplicateTicket):T.ok(l.array.slice(0,this.chainSpec.epochLength))}getTicketsMark(e){const t=this.getSlotPhaseIndex(this.state.timeslot),r=this.getSlotPhaseIndex(e);return this.isSameEpoch(e)&&t<this.chainSpec.contestLength&&this.chainSpec.contestLength<=r&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?this.outsideInSequencer(this.state.ticketsAccumulator):null}isExtrinsicLengthValid(e,t){return this.getSlotPhaseIndex(e)<this.chainSpec.contestLength?t.length<=this.chainSpec.maxTicketsPerExtrinsic:0===t.length}areTicketAttemptsValid(e){const t=e.length;for(let r=0;r<t;r++)if(e[r].attempt>=this.chainSpec.ticketsPerValidator)return!1;return!0}getSafroleSealState(e){const t=this.isEpochChanged(e),r=t?this.state.nextValidatorData:this.state.currentValidatorData,s=this.state.entropy[t?1:2];return{currentValidatorData:r,currentEntropy:this.state.entropy[t?2:3],sealingKeySeries:this.getSlotKeySequence(e,r,s)}}async transition(e){if(this.state.timeslot>=e.slot)return T.error(Jc.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return T.error(Jc.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return T.error(Jc.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot,e.punishSet);if(t.isError)return T.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,o=this.getEntropy(e.slot,e.entropy),a=this.getSlotKeySequence(e.slot,s,o[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,o[2]);if(c.isError)return T.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:o,sealingKeySeries:a,ticketsAccumulator:c.ok},h={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return T.ok(h)}}!function(e){e[e.InvalidValidatorIndex=0]="InvalidValidatorIndex",e[e.InvalidValidator=1]="InvalidValidator",e[e.InvalidTicket=2]="InvalidTicket",e[e.IncorrectSeal=3]="IncorrectSeal",e[e.IncorrectEntropySource=4]="IncorrectEntropySource"}(Yc||(Yc={}));class il{bandersnatch;constructor(e=zc.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=D.blobFromParts(Tc,r.ok.raw),i=await Pc(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,D.blobFromNumbers([]));return i.isError?T.error(Yc.IncorrectEntropySource):T.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return T.error(Yc.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),o=t.sealingKeySeries,a=t.currentEntropy;return o.kind===mi.Tickets?await this.verifySealWithTicket(o.tickets,n,a,r,s,e):await this.verifySealWithKeys(o.keys,i,n,a,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const o=t%e.length,{id:a,attempt:c}=e[o],l=D.blobFromParts(Dc,r.raw,new Uint8Array([c])),h=await Pc(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,Yr(n));return h.isError?T.error(Yc.IncorrectSeal):a.isEqualTo(h.ok)?T.ok(h.ok):T.error(Yc.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,o){if(!e[r%e.length].isEqualTo(t.bandersnatch))return T.error(Yc.InvalidValidator);const a=D.blobFromParts(Nc,s.raw),c=await Pc(await this.bandersnatch,i.map(e=>e.bandersnatch),n,o.seal.materialize(),a,Yr(o));return c.isError?T.error(Yc.IncorrectSeal):T.ok(c.ok)}}function nl(e){if(e.length===Xc.Requested)return{status:Xc.Requested};if(e.length===Xc.Available)return{status:Xc.Available,data:[e[0]]};if(e.length===Xc.Unavailable)return{status:Xc.Unavailable,data:[e[0],e[1]]};if(e.length===Xc.Reavailable)return{status:Xc.Reavailable,data:[e[0],e[1],e[2]]};throw new Error(`Invalid slots length: ${e.length}`)}!function(e){e[e.Requested=0]="Requested",e[e.Available=1]="Available",e[e.Unavailable=2]="Unavailable",e[e.Reavailable=3]="Reavailable"}(Xc||(Xc={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(Zc||(Zc={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(el||(el={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(tl||(tl={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(rl||(rl={}));class ol{source;destination;amount;memo;gas;static Codec=ke.Class(ol,{source:ke.u32.asOpaque(),destination:ke.u32.asOpaque(),amount:ke.u64,memo:ke.bytes(128),gas:ke.u64.asOpaque()});constructor(e,t,r,s,i){this.source=e,this.destination=t,this.amount=r,this.memo=s,this.gas=i}static create({source:e,destination:t,amount:r,memo:s,gas:i}){return new ol(e,t,r,s,i)}}class al{services;transfers;authorizationQueues=new Map;yieldedRoots=new Map;validatorsData=null;privilegedServices=null;constructor(e,t){this.services=e,this.transfers=t}static empty(){return new al({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new al(e,[])}static copyFrom(e){const t={servicesUpdates:[...e.services.servicesUpdates],servicesRemoved:[...e.services.servicesRemoved],preimages:[...e.services.preimages],storage:[...e.services.storage]},r=[...e.transfers],s=new al(t,r);for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return s.yieldedRoots=new Map(e.yieldedRoots),s.validatorsData=null===e.validatorsData?null:[...e.validatorsData],s.privilegedServices=null===e.privilegedServices?null:fi.create({...e.privilegedServices,authManager:[...e.privilegedServices.authManager]}),s}}class cl{state;stateUpdate;constructor(e,t=al.empty()){this.state=e,this.stateUpdate=t}getServiceInfo(e){if(null===e)return null;const t=this.stateUpdate.services.servicesRemoved.some(t=>t===e);if(t)return null;const r=this.stateUpdate.services.servicesUpdates.find(t=>t.serviceId===e);if(void 0!==r)return r.action.account;const s=this.state.getService(e);return null===s?null:s.getInfo()}getStorage(e,t){const r=this.stateUpdate.services.storage.find(r=>r.serviceId===e&&r.key.isEqualTo(t));if(void 0!==r)return r.value;const s=this.state.getService(e);return s?.getStorage(t)??null}hasPreimage(e,t){if(void 0!==this.stateUpdate.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}getPreimage(e,t){const r=this.stateUpdate.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t));if(void 0!==r&&r.action.kind===ki.Provide)return r.action.preimage.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}getLookupHistory(e,t,r,s){const i=this.stateUpdate.services.preimages.findLast(e=>e.serviceId===t&&e.hash.isEqualTo(r)&&BigInt(e.length)===s),n=()=>{const e=this.state.getService(t),i=function(e){return e>=2n**32n?null:se(Number(e))}(s);if(null===i||null===e)return null;const n=e.getLookupHistory(r,i);return null===n?null:new Ci(r,i,n)};if(void 0===i)return n();const{action:o}=i;switch(o.kind){case ki.Provide:return new Ci(r,i.length,Ei([e]));case ki.Remove:{const t=n();return null===t?null:new Ci(r,t.length,Ei([...t.slots,e]))}case ki.UpdateOrAdd:return o.item}w(o)}updateStorage(e,t,r){const s=null===r?Oi.remove({serviceId:e,key:t}):Oi.set({serviceId:e,storage:Si.create({key:t,value:r})}),i=this.stateUpdate.services.storage.findIndex(e=>e.serviceId===s.serviceId&&e.key.isEqualTo(t)),n=-1===i?0:1;this.stateUpdate.services.storage.splice(i,n,s)}updatePreimage(e){this.stateUpdate.services.preimages.push(e)}updateServiceStorageUtilisation(e,t,r,s){if(t.overflow||r.overflow)return T.error("insufficient funds");const i=vi.calculateThresholdBalance(t.value,r.value);return s.balance<i?T.error("insufficient funds"):(this.updateServiceInfo(e,vi.create({...s,storageUtilisationBytes:r.value,storageUtilisationCount:t.value})),T.ok(_))}updateServiceInfo(e,t){const r=this.stateUpdate.services.servicesUpdates.findIndex(t=>t.serviceId===e),s=-1===r?0:1,i=this.stateUpdate.services.servicesUpdates[r];i?.action.kind!==xi.Create?this.stateUpdate.services.servicesUpdates.splice(r,s,Ri.update({serviceId:e,serviceInfo:t})):this.stateUpdate.services.servicesUpdates.splice(r,s,Ri.create({serviceId:e,serviceInfo:t,lookupHistory:i.action.lookupHistory}))}getPrivilegedServices(){return null!==this.stateUpdate.privilegedServices?this.stateUpdate.privilegedServices:this.state.privilegedServices}}const ll=Js.new(void 0,"accumulate-externalities");class hl{chainSpec;updatedState;currentServiceId;currentTimeslot;checkpointedState=null;nextNewServiceId;constructor(e,t,r,s,i){if(this.chainSpec=e,this.updatedState=t,this.currentServiceId=r,this.currentTimeslot=i,this.nextNewServiceId=this.getNextAvailableServiceId(s),null===this.updatedState.getServiceInfo(this.currentServiceId))throw new Error(`Invalid state initialization. Service info missing for ${this.currentServiceId}.`)}getStateUpdates(){return[this.updatedState.stateUpdate,this.checkpointedState]}getNextNewServiceId(){return this.nextNewServiceId}getCurrentServiceInfo(){const e=this.updatedState.getServiceInfo(this.currentServiceId);if(null===e)throw new Error(`Missing service info for current service! ${this.currentServiceId}`);return e}getServiceInfo(e){return this.updatedState.getServiceInfo(e)}isPreviousCodeExpired(e,t,r){const s=this.updatedState.getLookupHistory(this.currentTimeslot,e,t,r),i=null===s?null:nl(s.slots);if(i?.status!==Xc.Unavailable)return[!1,"wrong status"];const n=this.currentTimeslot,o=i.data[1]<n-this.chainSpec.preimageExpungePeriod;return[o,o?"":"not expired"]}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=vr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:nl(r.slots)}requestPreimage(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null!==r){const e=r.slots.length;if(e===Xc.Requested)return T.error(Zc.AlreadyRequested);if(e===Xc.Available||e===Xc.Reavailable)return T.error(Zc.AlreadyAvailable);I(e===Xc.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,o=t-BigInt(r?.length??0),a=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(o)+(i?0n:81n);I(a>=0,`storageUtilisationCount has to be a positive number, got: ${a}`),I(c>=0,`storageUtilisationBytes has to be a positive number, got: ${c}`);const l=!ie(a),h=!oe(c),u=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,{overflow:l,value:l?se(0):a},{overflow:h,value:h?ne(0):c},s);if(u.isError)return T.error(Zc.InsufficientFunds,u.details);const d=ec(t);return null===r?this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new Ci(e,d,Ei([]))})):this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new Ci(e,d,Ei([...r.slots,this.currentTimeslot]))})),T.ok(_)}forgetPreimage(e,t){const r=this.currentServiceId,s=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null===s)return T.error(null);const i=nl(s.slots);if(i.status===Xc.Requested)return this.updatedState.updatePreimage(_i.remove({serviceId:r,hash:s.hash,length:s.length})),T.ok(_);const n=this.currentTimeslot;return i.status===Xc.Unavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(_i.remove({serviceId:r,hash:s.hash,length:s.length})),T.ok(_)):T.error(null):i.status===Xc.Available?(this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:r,lookupHistory:new Ci(s.hash,s.length,Ei([i.data[0],n]))})),T.ok(_)):i.status===Xc.Reavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:r,lookupHistory:new Ci(s.hash,s.length,Ei([i.data[2],n]))})),T.ok(_)):T.error(null):void w(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return T.error(el.DestinationNotFound);if(r<n.onTransferMinGas)return T.error(el.GasTooLow);const o=i.balance-t;return o<vi.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes)?T.error(el.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(ol.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...i,balance:ne(o)})),T.ok(_))}newService(e,t,r,s){const i=this.nextNewServiceId,n=se(2),o=ae(ne(81),t),a=ec(t),c=vi.calculateThresholdBalance(n,o.value),l=this.getCurrentServiceInfo(),h=vi.calculateThresholdBalance(l.storageUtilisationCount,l.storageUtilisationBytes),u=l.balance-c;return u<h||o.overflow?T.error("insufficient funds"):(this.updatedState.stateUpdate.services.servicesUpdates.push(Ri.create({serviceId:i,serviceInfo:vi.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),lookupHistory:new Ci(e.asOpaque(),a,Ei([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...l,balance:ne(u)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return vr(256+(e-256+42+t)%t)}(i)),T.ok(i))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...s,codeHash:e,accumulateMinGas:wr(t),onTransferMinGas:wr(r)}))}updateValidatorsData(e){const t=this.updatedState.getPrivilegedServices().validatorsManager;t===this.currentServiceId?this.updatedState.stateUpdate.validatorsData=e:ll.trace(`Current service id (${this.currentServiceId}) is not a validator manager (${t}) and cannot update validators. Ignoring.`)}checkpoint(){this.checkpointedState=al.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t){const r=this.updatedState.getPrivilegedServices().authManager[e];r===this.currentServiceId?this.updatedState.stateUpdate.authorizationQueues.set(e,t):ll.trace(`Current service id (${this.currentServiceId}) is not an auth manager of core ${e} (expected: ${r}) and cannot update authorization queue. Ignoring`)}updatePrivilegedServices(e,t,r,s){const i=this.updatedState.getPrivilegedServices().manager;i===this.currentServiceId?this.updatedState.stateUpdate.privilegedServices=fi.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>gi.create({service:e,gasLimit:t}))}):ll.trace(`Current service id (${this.currentServiceId}) is not a manager (${i}) and cannot update privileged services. Ignoring.`)}yield(e){this.updatedState.stateUpdate.yieldedRoots.set(this.currentServiceId,e)}providePreimage(e,t){if(null===(null===e?null:this.updatedState.state.getService(e))||null===e)return T.error(rl.ServiceNotFound);const r=Ge(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,ne(t.length));return null!==s&&Ci.isRequested(s)?this.updatedState.hasPreimage(e,r)?T.error(rl.AlreadyProvided):(this.updatedState.updatePreimage(_i.provide({serviceId:e,preimage:wi.create({hash:r,blob:t}),slot:this.currentTimeslot})),T.ok(_)):T.error(rl.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return T.error(tl.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=M.zero(Ne).asOpaque();if(Za(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return T.error(tl.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return T.error(tl.InvalidPreimage,"Too many storage items");const n=ne(81),o=ne(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,n)-n),[a,c]=this.isPreviousCodeExpired(e,t,o);if(!a)return T.error(tl.InvalidPreimage,`Previous code available: ${c}`);const l=ae(s.balance,r.balance);return l.overflow?T.error(tl.InvalidService,"Balance overflow"):(this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...s,balance:l.value})),this.updatedState.stateUpdate.services.servicesRemoved.push(e),T.ok(_))}read(e,t){return null===e?null:this.updatedState.getStorage(e,t)}write(e,t){const r=this.read(this.currentServiceId,e),s=null===r&&null!==t,i=null!==r&&null===t,n=s?1:i?-1:0,o=(t?.length??0)-(r?.length??0),a=s?BigInt(Ne):i?BigInt(-32):0n,c=this.getCurrentServiceInfo(),l=c.storageUtilisationCount+n,h=c.storageUtilisationBytes+BigInt(o)+a;I(l>=0,`storageUtilisationCount has to be a positive number, got: ${l}`),I(h>=0,`storageUtilisationBytes has to be a positive number, got: ${h}`);const u=!ie(l),d=!oe(h),g=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,{overflow:u,value:u?se(0):l},{overflow:d,value:d?ne(0):h},c);return g.isError?T.error("full",g.details):(this.updatedState.updateStorage(this.currentServiceId,e,t),T.ok(_))}readSnapshotLength(e){const t=this.updatedState.state.getService(this.currentServiceId);return t?.getStorage(e)?.length??null}lookup(e,t){return null===e?null:this.updatedState.getPreimage(e,t)}}function ul(e){const t=e.map(e=>e.workPackageSpec.hash);return gt.from(t)}const dl=ke.object({serviceId:ke.u32.asOpaque(),entropy:ke.bytes(Ne).asOpaque(),timeslot:ke.u32.asOpaque()}),gl=ke.object({serviceId:ke.u32.convert(e=>e,e=>e),gas:ke.u64.convert(e=>ne(e),e=>wr(e))});class fl{currentServiceId;index=Zn(0);gasCost=fo(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,ne(e.get())),Promise.resolve(void 0)}}const pl=fe(yi.Codec.sizeHint),yl=e=>ne(e);var ml,bl,Al;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(ml||(ml={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(bl||(bl={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class Il{currentServiceId;fetch;index=Zn(18);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=ne(s?.length??0),o=he(t.get(8),n),a=he(t.get(9),ne(n-o)),c=null===s?new Uint8Array:s.raw.subarray(Number(o),Number(o+a));if(r.storeFrom(i,c).isError)return eo.Panic;t.set(7,null===s?qa.NONE:n)}getValue(e){const t=ec(e.get(10));if(t===Al.Constants)return this.fetch.constants();if(t===Al.Entropy)return this.fetch.entropy();if(t===Al.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===Al.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===Al.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===Al.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===Al.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===Al.WorkPackage)return this.fetch.workPackage();if(t===Al.Authorizer)return this.fetch.authorizer();if(t===Al.AuthorizationToken)return this.fetch.authorizationToken();if(t===Al.RefineContext)return this.fetch.refineContext();if(t===Al.AllWorkItems)return this.fetch.allWorkItems();if(t===Al.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===Al.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===Al.AllOperands)return this.fetch.allOperands();if(t===Al.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===Al.AllTransfers)return this.fetch.allTransfers();if(t===Al.OneTransfer){const t=e.get(11);return this.fetch.oneTransfer(t)}return null}}!function(e){e[e.Constants=0]="Constants",e[e.Entropy=1]="Entropy",e[e.AuthorizerTrace=2]="AuthorizerTrace",e[e.OtherWorkItemExtrinsics=3]="OtherWorkItemExtrinsics",e[e.MyExtrinsics=4]="MyExtrinsics",e[e.OtherWorkItemImports=5]="OtherWorkItemImports",e[e.MyImports=6]="MyImports",e[e.WorkPackage=7]="WorkPackage",e[e.Authorizer=8]="Authorizer",e[e.AuthorizationToken=9]="AuthorizationToken",e[e.RefineContext=10]="RefineContext",e[e.AllWorkItems=11]="AllWorkItems",e[e.OneWorkItem=12]="OneWorkItem",e[e.WorkItemPayload=13]="WorkItemPayload",e[e.AllOperands=14]="AllOperands",e[e.OneOperand=15]="OneOperand",e[e.AllTransfers=16]="AllTransfers",e[e.OneTransfer=17]="OneTransfer"}(Al||(Al={}));class vl{currentServiceId;account;index=Zn(4);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),o=null===n?D.empty():me.encodeObject(wl,{...n,thresholdBalance:vi.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes)});if(r.storeFrom(i,o.raw).isError)return eo.Panic;null!==n?t.set(7,qa.OK):t.set(7,qa.NONE)}}const wl=ke.object({codeHash:ke.bytes(Ne),balance:ke.u64,thresholdBalance:ke.u64,accumulateMinGas:ke.u64.convert(e=>e,wr),onTransferMinGas:ke.u64.convert(e=>e,wr),storageUtilisationBytes:ke.u64,storageUtilisationCount:ke.u32},"ServiceAccountInfoWithThresholdBalance"),Sl=Js.new(void 0,"host-calls"),El=new TextDecoder("utf8");class Cl{currentServiceId;index=Zn(100);gasCost=fo(0);constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=t.get(11),c=new Uint8Array(ec(n)),l=new Uint8Array(ec(a));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,o),Sl.trace(`[${this.currentServiceId}] [${s}] ${El.decode(c)} ${El.decode(l)}`),Promise.resolve(void 0)}}class kl{currentServiceId;account;index=Zn(1);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=M.zero(Ne);if(r.loadInto(o.raw,i).isError)return eo.Panic;const a=this.account.lookup(s,o),c=ne(null===a?0:a.raw.length),l=t.get(10),h=t.get(11),u=he(l,c),d=he(h,ne(c-u)),g=null===a?new Uint8Array(0):a.raw.subarray(Number(u),Number(u+d));if(r.storeFrom(n,g).isError)return eo.Panic;null!==a?t.set(7,c):t.set(7,qa.NONE)}}class xl{currentServiceId;account;index=Zn(2);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=t.get(10),a=ec(n),c=new Uint8Array(4+a);if(null!==s&&Za(s,c),r.loadInto(c.subarray(4),i).isError)return eo.Panic;const l=Ge(c),h=this.account.read(s,l),u=ne(null===h?0:h.raw.length),d=t.get(11),g=t.get(12),f=he(d,u),p=he(g,ne(u-f)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(f),Number(f+p));if(r.storeFrom(o,y).isError)return eo.Panic;null!==h?t.set(7,u):t.set(7,qa.NONE)}}class Bl{currentServiceId;account;index=Zn(3);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=ec(i),c=new Uint8Array(4+a);if(Za(this.currentServiceId,c),r.loadInto(c.subarray(4),s).isError)return eo.Panic;const l=Ge(c),h=ec(o),u=new Uint8Array(h);if(r.loadInto(u,n).isError)return eo.Panic;const d=0n===o?null:D.blobFrom(u);if(this.account.write(l,d).isError)return void t.set(7,qa.FULL);const g=this.account.readSnapshotLength(l);t.set(7,null===g?qa.NONE:ne(g))}}const _l=[class{currentServiceId;partialState;chainSpec;index=Zn(5);gasCost=fo(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=Xa(t.get(7)),i=Xa(t.get(8)),n=Xa(t.get(9)),o=t.get(10),a=t.get(11),c=new Array,l=new Uint8Array(fe(gl.sizeHint)),h=ue.fromBlob(l);let u=o;for(let e=0n;e<a;e+=1n){if(h.resetTo(0),r.loadInto(l,u).isError)return eo.Panic;const{serviceId:e,gas:t}=h.object(gl);c.push([e,t]),u=ne(u+ne(h.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,ai(new Array(this.chainSpec.coresCount).fill(i),this.chainSpec),n,c),t.set(7,qa.OK)):t.set(7,qa.WHO)}},class{currentServiceId;partialState;chainSpec;index=Zn(6);gasCost=fo(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=new Uint8Array(2560);if(r.loadInto(n,i).isError)return eo.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,qa.CORE);const o=ue.fromBlob(n).sequenceFixLen(ke.bytes(Ne),80),a=pt.new(o,80);t.set(7,qa.OK),this.partialState.updateAuthorizationQueue(Sr(Number(s)),a)}},class{currentServiceId;partialState;chainSpec;index=Zn(7);gasCost=fo(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=new Uint8Array(pl*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return eo.Panic;const n=ue.fromBlob(i).sequenceFixLen(yi.Codec,this.chainSpec.validatorsCount);t.set(7,qa.OK),this.partialState.updateValidatorsData(Cr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Zn(8);gasCost=fo(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new fl(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Zn(9);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=wr(t.get(9)),o=wr(t.get(10)),a=M.zero(Ne);if(r.loadInto(a.raw,s).isError)return eo.Panic;const c=this.partialState.newService(a.asOpaque(),i,n,o);c.isOk?t.set(7,ne(c.ok)):t.set(7,qa.CASH)}},class{currentServiceId;partialState;index=Zn(10);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=M.zero(Ne);if(r.loadInto(o.raw,s).isError)return eo.Panic;this.partialState.upgradeService(o.asOpaque(),i,n),t.set(7,qa.OK)}},class{currentServiceId;partialState;index=Zn(11);gasCost=e=>{const t=10n+e.get(9);return yo(t)};constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Xa(t.get(7)),i=t.get(8),n=wr(t.get(9)),o=t.get(10),a=M.zero(128);if(r.loadInto(a.raw,o).isError)return eo.Panic;const c=this.partialState.transfer(s,i,n,a);if(c.isOk)return void t.set(7,qa.OK);const l=c.error;l!==el.DestinationNotFound?l!==el.GasTooLow?l!==el.BalanceBelowThreshold?w(l):t.set(7,qa.CASH):t.set(7,qa.LOW):t.set(7,qa.WHO)}},class{currentServiceId;partialState;index=Zn(12);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Xa(t.get(7)),i=t.get(8),n=M.zero(Ne).asOpaque();if(r.loadInto(n.raw,i).isError)return eo.Panic;if(s===this.currentServiceId)return void t.set(7,qa.WHO);const o=this.partialState.eject(s,n);if(o.isOk)return void t.set(7,qa.OK);const a=o.error;a===tl.InvalidService?t.set(7,qa.WHO):a===tl.InvalidPreimage?t.set(7,qa.HUH):w(a)}},class{currentServiceId;partialState;index=Zn(13);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=M.zero(Ne);if(r.loadInto(n.raw,s).isError)return eo.Panic;const o=this.partialState.checkPreimageStatus(n.asOpaque(),i),a=ne(0n);if(null===o)return t.set(7,qa.NONE),void t.set(8,a);switch(o.status){case Xc.Requested:return t.set(7,a),void t.set(8,a);case Xc.Available:return t.set(7,ne(1n+(BigInt(o.data[0])<<32n))),void t.set(8,a);case Xc.Unavailable:return t.set(7,ne(2n+(BigInt(o.data[0])<<32n))),void t.set(8,ne(o.data[1]));case Xc.Reavailable:return t.set(7,ne(3n+(BigInt(o.data[0])<<32n))),void t.set(8,ne((BigInt(o.data[2])<<32n)+BigInt(o.data[1])))}}},class{currentServiceId;partialState;index=Zn(14);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=M.zero(Ne);if(r.loadInto(n.raw,s).isError)return eo.Panic;const o=this.partialState.requestPreimage(n.asOpaque(),i);if(o.isOk)return void t.set(7,qa.OK);const a=o.error;a!==Zc.AlreadyAvailable&&a!==Zc.AlreadyRequested?a!==Zc.InsufficientFunds?w(a):t.set(7,qa.FULL):t.set(7,qa.HUH)}},class{currentServiceId;partialState;index=Zn(15);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=M.zero(Ne);if(r.loadInto(n.raw,s).isError)return eo.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,qa.OK):t.set(7,qa.HUH)}},class{currentServiceId;partialState;index=Zn(16);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=M.zero(Ne);if(r.loadInto(i.raw,s).isError)return eo.Panic;this.partialState.yield(i),t.set(7,qa.OK)}},class{currentServiceId;partialState;index=Zn(27);gasCost=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=ec(t.get(9)),o=D.blobFrom(new Uint8Array(n));if(r.loadInto(o.raw,i).isError)return eo.Panic;const a=this.partialState.providePreimage(s,o);if(a.isOk)return void t.set(7,qa.OK);const c=a.error;c!==rl.ServiceNotFound?c!==rl.WasNotRequested&&c!==rl.AlreadyProvided?w(c):t.set(7,qa.HUH):t.set(7,qa.WHO)}}];var Rl;!function(e){e.IS_AUTHORIZED=yl(0),e.REFINE=yl(0),e.ACCUMULATE=yl(5),e.ON_TRANSFER=yl(10)}(Rl||(Rl={}));class Ol{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new ja(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new rc(...t),this.pvm=new $a(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=_l.map(s=>new s(e,t.partialState,r)),i=[new Cl(e),new fl(e),new xl(e,t.serviceExternalities),new Bl(e,t.serviceExternalities),new Il(e,t.fetchExternalities),new kl(e,t.serviceExternalities),new vl(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new Cl(e),new fl(e),new xl(e,t.partialState),new Bl(e,t.partialState),new kl(e,t.partialState),new vl(e,t.partialState)]}async run(e,t){const r=fc.fromSpi(this.serviceCode.raw,e.raw,!0);return this.pvm.runProgram(r.code,Number(this.entrypoint),t,r.registers,r.memory)}static createAccumulateExecutor(e,t,r,s){const i=Ol.prepareAccumulateHostCalls(e,r,s);return new Ol(t,i,Rl.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=Ol.prepareOnTransferHostCalls(e,r);return new Ol(t,s,Rl.ON_TRANSFER)}}const Ul=ke.object({timeslot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),transfers:ke.sequenceVarLen(ol.Codec)});var Tl;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(Tl||(Tl={}));const Nl=Js.new(void 0,"deferred-transfers");class Dl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition({pendingTransfers:e,timeslot:t,servicesUpdate:r}){const s=new Map,i=function(e){const t=new Set;for(const r of e)t.add(r);return Array.from(t)}(e.flatMap(e=>[e.source,e.destination])),n=new cl(this.state,al.new(r));for(const r of i){const i=e.filter(e=>e.destination===r),o=new hl(this.chainSpec,n,r,r,t),a=o.getServiceInfo(r);if(null===a)return T.error(Tl.ServiceInfoNotExist);const c=a.codeHash,l=n.getPreimage(r,c.asOpaque()),h=ae(a.balance,...i.map(e=>e.amount));if(h.overflow)return T.error(Tl.ServiceBalanceOverflow);const u=vi.create({...a,balance:h.value});if(n.updateServiceInfo(r,u),null===l||0===i.length){Nl.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`),s.set(r,{count:se(i.length),gasUsed:wr(0)});continue}const d=Ol.createOnTransferExecutor(r,l,{partialState:o}),g=me.encodeObject(Ul,{timeslot:t,serviceId:r,transfers:i},this.chainSpec),f=i.reduce((e,t)=>e+t.gas,0n),{consumedGas:p}=await d.run(g,yo(f));s.set(r,{count:se(i.length),gasUsed:wr(p)})}return T.ok({servicesUpdate:r,transferStatistics:s})}}class Ml extends k{static Codec=ke.Class(Ml,{hash:ke.bytes(Ne).asOpaque(),exportsRoot:ke.bytes(Ne).asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),payloadHash:ke.bytes(Ne),gas:ke.varU64.asOpaque(),result:Hr.Codec,authorizationOutput:ke.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:o}){return new Ml({gas:wr(s),payloadHash:n.asOpaque(),result:o,authorizationOutput:D.blobFrom(e.raw),exportsRoot:r.asOpaque(),hash:i.asOpaque(),authorizerHash:t.asOpaque()})}constructor(e){super(),this.gas=e.gas,this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Ml(e)}}class Pl{static Codec=ke.Class(Pl,{hash:ke.bytes(Ne).asOpaque(),exportsRoot:ke.bytes(Ne).asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),authorizationOutput:ke.blob,payloadHash:ke.bytes(Ne),result:Hr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new Pl({payloadHash:i,result:n,authorizationOutput:e,exportsRoot:r,hash:s,authorizerHash:t})}constructor(e){this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Pl(e)}}class Ll{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new Ll([],se(0),wr(0n))}}class Hl{reportsDataByServiceId;autoAccumulateServicesByServiceId;serviceIds;constructor(e,t){const{autoAccumulateServicesByServiceId:r,serviceIds:s}=this.transformAutoAccumulateServices(t);this.autoAccumulateServicesByServiceId=r;const{reportsDataByServiceId:i,serviceIds:n}=this.transformReports(e);this.reportsDataByServiceId=i,this.serviceIds=this.mergeServiceIds(n,s)}mergeServiceIds(e,t){const r=new Set;for(const t of e)r.add(t);for(const e of t)r.add(e);return Array.from(r)}transformAutoAccumulateServices(e){const t=new Set,r=new Map;for(const s of e)r.set(s.service,s),t.add(s.service);return{autoAccumulateServicesByServiceId:r,serviceIds:t}}transformReports(e){const t=new Map,r=new Set;for(const s of e)for(const e of s.results){const i=e.serviceId;r.add(i);const n=t.get(i)??Ll.empty();n.reportsLength=se(n.reportsLength+1),n.gasCost=wr(n.gasCost+e.gas),n.operands.push(Ml.new({gas:e.gas,payloadHash:e.payloadHash,result:e.result,authorizationOutput:s.authorizationOutput,exportsRoot:s.workPackageSpec.exportsRoot,hash:s.workPackageSpec.hash,authorizerHash:s.authorizerHash})),t.set(i,n)}for(const e of r){const r=t.get(e)??null,s=this.autoAccumulateServicesByServiceId.get(e)??null;null!==r&&null!==s&&(r.gasCost=wr(r.gasCost+s.gasLimit))}return{reportsDataByServiceId:t,serviceIds:r}}getOperands(e){return this.reportsDataByServiceId.get(e)?.operands??[]}getReportsLength(e){return this.reportsDataByServiceId.get(e)?.reportsLength??se(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??wr(0n)}getServiceIds(){return this.serviceIds}}class Kl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getWorkReportsToAccumulateImmediately(e){return e.filter(e=>0===e.context.prerequisites.length&&0===e.segmentRootLookup.length)}getWorkReportDependencies(e){return Array.from(gt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return Vl(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>Gi.create({report:e,dependencies:this.getWorkReportDependencies(e)})),gt.from(t))}enqueueReports(e){const t=[];let r=[...e];for(;r.length>0;){const e=r.filter(({dependencies:e})=>0===e.length).map(({report:e})=>e);if(0===e.length)return t;t.push(...e),r=Vl(r,ul(e))}return t}getQueueFromState(e){const t=e%this.chainSpec.epochLength,r=this.state.accumulationQueue.slice(t),s=this.state.accumulationQueue.slice(0,t);return r.concat(s).flat()}}function Vl(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return Gi.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}var Ql;!function(e){e[e.InvalidAnchor=0]="InvalidAnchor",e[e.InvalidOrder=1]="InvalidOrder",e[e.InvalidSignature=2]="InvalidSignature",e[e.NoReportPending=3]="NoReportPending",e[e.InvalidValidatorIndex=4]="InvalidValidatorIndex"}(Ql||(Ql={}));class Fl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition(e){const t=this.chainSpec.coresCount,r=this.verifySignatures(e.assurances),s=e.assurances.map(e=>e.materialize()),i=pt.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:o,bitfield:a}=r;if(!s.isEqualTo(e.parentHash))return T.error(Ql.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return T.error(Ql.InvalidOrder,`order: expected: ${n+1}, got: ${o}`);n=r.validatorIndex,I(a.bitLength===t,`Invalid bitfield length of ${a.bitLength}`);const c=a.indicesOfSetBits();for(const e of c)i[e]+=1}const o=[],a=[],c=this.chainSpec.validatorsSuperMajority;for(let r=0;r<t;r++){const t=i[r],s=this.state.availabilityAssignment[r],n=null!==s;if(t>0&&!n)return T.error(Ql.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&a.push(r),t>=c&&(o.push(s.workReport.data),a.push(r)))}const l=await r;if(l.isError)return l;const h=this.state.availabilityAssignment.slice();for(const e of a)h[e]=null;return T.ok({availableReports:o,stateUpdate:{availabilityAssignment:h}})}async verifySignatures(e){const t=this.state.currentValidatorData,r=[];for(const s of e){const e=s.view(),i=t[e.validatorIndex.materialize()];if(void 0===i)return T.error(Ql.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:$l(e.anchor.encoded(),e.bitfield.encoded())})}const s=await hr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return T.error(Ql.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return T.ok(_)}}const Gl=D.blobFromString("jam_available").raw;function $l(e,t){return D.blobFromParts(Gl,Ge(D.blobFromParts(e.raw,t.raw)).raw)}const jl=D.blobFromString("peak");class ql{hasher;mountains;static empty(e){return new ql(e)}static fromPeaks(e,t){return new ql(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(zl.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=zl.fromPeak(e,1);for(;;){const e=this.mountains.pop();if(void 0===e)return void this.mountains.push(t);if(e.size!==t.size)return this.mountains.push(e),void this.mountains.push(t);t=e.mergeWith(this.hasher,t)}}getSuperPeakHash(){if(0===this.mountains.length)return M.zero(Ne).asOpaque();const e=this.mountains.slice().reverse(),t=e.length;let r=e[0].peak;for(let s=1;s<t;s++){const t=e[s];r=this.hasher.hashConcatPrepend(jl,r,t.peak)}return r}getPeaks(){const e=[],t=this.mountains;let r=1,s=t.length-1;for(;s>=0;){const i=t[s];i.size>=r&&i.size<2*r?(e.push(i.peak),s-=1):e.push(null),r<<=1}return{peaks:e}}}class zl{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new zl(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new zl(i,n)}mergeWith(e,t){return zl.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var Wl;!function(e){e[e.BadCoreIndex=0]="BadCoreIndex",e[e.FutureReportSlot=1]="FutureReportSlot",e[e.ReportEpochBeforeLast=2]="ReportEpochBeforeLast",e[e.InsufficientGuarantees=3]="InsufficientGuarantees",e[e.OutOfOrderGuarantee=4]="OutOfOrderGuarantee",e[e.NotSortedOrUniqueGuarantors=5]="NotSortedOrUniqueGuarantors",e[e.WrongAssignment=6]="WrongAssignment",e[e.CoreEngaged=7]="CoreEngaged",e[e.AnchorNotRecent=8]="AnchorNotRecent",e[e.BadServiceId=9]="BadServiceId",e[e.BadCodeHash=10]="BadCodeHash",e[e.DependencyMissing=11]="DependencyMissing",e[e.DuplicatePackage=12]="DuplicatePackage",e[e.BadStateRoot=13]="BadStateRoot",e[e.BadBeefyMmrRoot=14]="BadBeefyMmrRoot",e[e.CoreUnauthorized=15]="CoreUnauthorized",e[e.BadValidatorIndex=16]="BadValidatorIndex",e[e.WorkReportGasTooHigh=17]="WorkReportGasTooHigh",e[e.ServiceItemGasTooLow=18]="ServiceItemGasTooLow",e[e.TooManyDependencies=19]="TooManyDependencies",e[e.SegmentRootLookupInvalid=20]="SegmentRootLookupInvalid",e[e.BadSignature=21]="BadSignature",e[e.WorkReportTooBig=22]="WorkReportTooBig"}(Wl||(Wl={}));const Jl=ke.object({B_I:ke.u64,B_L:ke.u64,B_S:ke.u64,C:ke.u16,D:ke.u32,E:ke.u32,G_A:ke.u64,G_I:ke.u64,G_R:ke.u64,G_T:ke.u64,H:ke.u16,I:ke.u16,J:ke.u16,L:ke.u32,O:ke.u16,P:ke.u16,Q:ke.u16,R:ke.u16,S:ke.u16,T:ke.u16,U:ke.u16,V:ke.u16,W_A:ke.u16,W_B:ke.u32,W_C:ke.u32,W_E:ke.u32,W_G:ke.u32,W_M:ke.u32,W_P:ke.u32,W_R:ke.u32,W_T:ke.u32,W_X:ke.u32,Y:ke.u32}),Yl=new Map;class Xl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=Yl.get(e);if(void 0!==t)return t;const r=me.encodeObject(Jl,{B_I:ne(10n),B_L:ne(1n),B_S:ne(100n),C:te(e.coresCount),D:se(e.preimageExpungePeriod),E:se(e.epochLength),G_A:ne(eh),G_I:ne(5e7),G_R:ne(5e9),G_T:ne(th),H:te(8),I:te(Dr),J:te(8),L:se(14400),O:te(8),P:te(e.slotDuration),Q:te(80),R:te(0),S:te(1024),T:te(e.rotationPeriod),U:te(5),V:te(0),W_A:te(e.validatorsCount),W_B:se(13794305),W_C:se(4e6),W_E:se(684),W_G:se(4104),W_M:se(3072),W_P:se(6),W_R:se(49152),W_T:se(128),W_X:se(3072),Y:se(e.contestLength)});return Yl.set(e,r),r}(this.chainSpec)}entropy(){return this.entropyHash.asOpaque()}authorizerTrace(){return null}workItemExtrinsic(e,t){return null}workItemImport(e,t){return null}workPackage(){return null}authorizer(){return null}authorizationToken(){return null}refineContext(){return null}allWorkItems(){return null}oneWorkItem(e){return null}workItemPayload(e){return null}allOperands(){return A.is(h.V0_6_4)?me.encodeObject(ke.sequenceVarLen(Pl.Codec),this.operands,this.chainSpec):me.encodeObject(ke.sequenceVarLen(Ml.Codec),this.operands,this.chainSpec)}oneOperand(e){if(e>=2n**32n)return null;const t=this.operands[Number(e)];return void 0===t?null:A.isGreaterOrEqual(h.V0_6_5)?me.encodeObject(Ml.Codec,t,this.chainSpec):me.encodeObject(Pl.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}var Zl;!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(Zl||(Zl={}));const eh=10000000n,th=3500000000n,rh=Js.new(void 0,"accumulate"),sh=ke.object({slot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),operands:ke.sequenceVarLen(Pl.Codec)}),ih=ke.object({slot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),operands:ke.sequenceVarLen(Ml.Codec)}),nh=ke.object({slot:ke.varU32.asOpaque(),serviceId:ke.varU32.asOpaque(),operands:ke.varU32});class oh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}findReportCutoffIndex(e,t){const r=t.length;let s=0n;for(let i=0;i<r;i++){const r=t[i].results.map(e=>e.gas).reduce((e,t)=>e+t,0n);if(s+r>e)return i;s+=r}return r}async pvmAccumulateInvocation(e,t,r,s,i,n){const o=this.state.getService(t);if(null===o)return rh.log(`Service with id ${t} not found.`),T.error(Zl.NoService);const a=o.getInfo().codeHash,c=o.getPreimage(a.asOpaque());if(null===c)return rh.log(`Code with hash ${a} not found for service ${t}.`),T.error(Zl.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=le(Ge(me.encodeObject(dl,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return vr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),u=new hl(this.chainSpec,new cl(this.state,n),t,l,e),d={partialState:u,serviceExternalities:u,fetchExternalities:new Xl(i,r,this.chainSpec)},g=Ol.createAccumulateExecutor(t,c,d,this.chainSpec);let f=D.empty();f=A.is(h.V0_6_4)?me.encodeObject(sh,{slot:e,serviceId:t,operands:r},this.chainSpec):A.is(h.V0_6_5)?me.encodeObject(ih,{slot:e,serviceId:t,operands:r},this.chainSpec):me.encodeObject(nh,{slot:e,serviceId:t,operands:se(r.length)});const p=await g.run(f,yo(s)),[y,m]=u.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===Yn.OOG||e===Yn.PANIC)return T.ok({stateUpdate:m,consumedGas:wr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Ne){const e=M.fromBlob(p.memorySlice,Ne);y.yieldedRoots.set(t,e.asOpaque())}return T.ok({stateUpdate:y,consumedGas:wr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){rh.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const o=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return o.isError?(rh.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(rh.trace(`Accumulation successful for ${e}.`),o.ok)}async accumulateSequentially(e,t,r,s,i,n){const o=this.findReportCutoffIndex(e,t);if(0===o)return{accumulatedReports:se(0),gasCost:wr(0),state:n};const a=t.slice(0,o),c=this.state.privilegedServices.autoAccumulateServices,l=new Hl(a,c),h=t.slice(o),{gasCost:u,state:d,...g}=await this.accumulateInParallel(l,r,s,i,n);S(g);const{accumulatedReports:f,gasCost:p,state:y,...m}=await this.accumulateSequentially(wr(e-u),h,r,s,i,d);return S(m),{accumulatedReports:se(o+f),gasCost:wr(u+p),state:y}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds();let o=wr(0),a=i;for(const i of n){const n=al.copyFrom(a),{consumedGas:c,stateUpdate:l}=await this.accumulateSingleService(i,e.getOperands(i),e.getGasCost(i),t,r,a);o=wr(o+c);const h=s.get(i)??{count:se(0),gasUsed:wr(0)};h.count=se(h.count+e.getReportsLength(i)),h.gasUsed=wr(h.gasUsed+c),s.set(i,h),a=null===l?n:l}return{state:a,gasCost:o}}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=ul(e),o=Array.from(n).sort((e,t)=>di(e,t).value),a=xr(this.state.recentlyAccumulated.slice(1).concat(gt.from(o)),this.chainSpec),c=this.state.accumulationQueue.slice();c[i]=Vl(t,n);for(let e=1;e<s;e++)if(e<r-this.state.timeslot)c[(i+s-e)%s]=[];else{const t=(i+s-e)%s;c[t]=Vl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:xr(c,this.chainSpec),timeslot:r}}getGasLimit(){const e=eh*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=wr(th>e?th:e);return wr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new Kl(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),o=i.getWorkReportsToAccumulateLater(e),a=Vl(i.getQueueFromState(t).concat(o),ul(n)),c=i.enqueueReports(a),l=n.concat(c),h=this.getGasLimit(),{accumulatedReports:u,gasCost:d,state:g,...f}=await this.accumulateSequentially(h,l,t,r,s,al.empty());S(f);const p=l.slice(0,u),y=this.getAccumulationStateUpdate(p,o,t),m=await async function(e){const t=await ht.create(),r=(s=t,{hashConcat:(e,t=[])=>ut(s,[e,...t].map(D.blobFrom)).asOpaque()});var s;return function(e,t){return 1===e.length?t.hashConcat(e[0].raw):function e(t,r){if(0===t.length)return M.zero(Ne).asOpaque();if(1===t.length)return t[0];const s=Math.ceil(t.length/2),i=t.slice(0,s),n=t.slice(s);return r.hashConcat(D.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>D.blobFromParts([ce(e),t.raw])),r)}(Array.from(g.yieldedRoots.entries()));return T.ok({root:m,stateUpdate:{...y,...g.services},accumulationStatistics:s,pendingTransfers:g.transfers})}}class ah{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=Sr(0);r<this.chainSpec.coresCount;r++){let s=t[r].slice();const i=this.state.authQueues[r],n=e.used.get(r);for(void 0!==n&&(s=s.filter(e=>!n.delete(e))),s.push(i[e.slot%80]);s.length>8;)s.shift();t[r]=ft(s)}return{authPools:ai(t,this.chainSpec)}}}class ch{hasher;state;constructor(e,t){this.hasher=e,this.state=t}transition(e){const t=this.state.recentBlocks.slice(),r=t.length>0?t[t.length-1]:null;null!==r&&(r.postStateRoot=e.priorStateRoot);const s=null!==r?ql.fromPeaks(this.hasher,r.mmr):ql.empty(this.hasher);return s.append(e.accumulateRoot),t.push({headerHash:e.headerHash,mmr:s.getPeaks(),postStateRoot:M.zero(Ne).asOpaque(),reported:e.workPackages}),t.length>8&&t.shift(),{recentBlocks:t}}}function lh(e,t,r){return function(e,t,r){const s=hh(Ar(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){I(32===t.length,`Expected entropy of length 32, got ${t.length}`);const r=e.length,s=function(e,t){const r=new Array(t),s=new Uint8Array(36);s.set(e.raw);for(let e=0;e<t;e++){s.set(ce(se(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=le(Ge(s).raw.subarray(t,i))>>>0;r[e]=n}return r}(t,e.length),i=new Array(r);let n=r;for(let t=0;t<r;t++){const r=s[t]%n;i[t]=e[r],n--,e[r]=e[n],e.length=n}return i}(Array(r.validatorsCount).fill(0).map((e,t)=>Sr(Math.floor(t*r.coresCount/r.validatorsCount))),e),o=s,a=r.coresCount,n.map(e=>(e+o)%a));var n,o,a;return i}(t,r,e)}function hh(e,t){return Math.floor(e/t)}const uh=D.blobFromString("jam_guarantee").raw;function dh(e){return D.blobFromParts(uh,e.raw)}const gh=1e7;class fh{chainSpec;state;mmrHasher;headerChain;constructor(e,t,r,s){this.chainSpec=e,this.state=t,this.mmrHasher=r,this.headerChain=s}async transition(e){const t=function(e,t){const r=t.coresCount;let s=-1;for(const t of e){const e=t.view().report.view().coreIndex.materialize();if(s>=e)return T.error(Wl.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return T.error(Wl.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return T.ok(_)}(e.guarantees,this.chainSpec);if(t.isError)return t;const r=function(e){for(const t of e){const e=t.view().report.view(),r=e.context.view().prerequisites.view().length,s=e.segmentRootLookup.view().length;if(r+s>8)return T.error(Wl.TooManyDependencies,`Report at ${e.coreIndex.materialize()} has too many dependencies. Got ${r} + ${s}, max: 8`);const i=e.authorizationOutput.view().length;let n=0;for(const t of e.results.view())n+=t.view().result.view().okBlob?.raw.length??0;if(i+n>49152)return T.error(Wl.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return T.ok(_)}(e.guarantees);if(r.isError)return r;const s=this.workReportHashes(e.guarantees),i=this.verifyCredentials(e,s);if(i.isError)return i;const n=hr(i.ok),o=this.verifyPostSignatureChecks(e.guarantees);if(o.isError)return o;const a=this.verifyContextualValidity(e);if(a.isError)return a;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const h=this.state.availabilityAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];h[r.coreIndex]=ni.create({workReport:new Me(i,r),timeout:e.slot}),l+=1}return T.ok({stateUpdate:{availabilityAssignment:ai(h,this.chainSpec)},reported:a.ok,reporters:mt.fromArray(q,i.ok.map(e=>e.key)).slice()})}workReportHashes(e){const t=[];for(const r of e)t.push(x(Ge(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let o=0;for(const r of e){const e=r.view(),a=e.report.view().coreIndex.materialize(),c=t[o];o+=1;const l=e.credentials.view();if(l.length<$r[0]||l.length>$r[1])return T.error(Wl.InsufficientGuarantees,`Invalid number of credentials. Expected ${$r}, got ${l.length}`);const h=s(n,e.slot.materialize());if(h.isError)return h;const u=h.ok;let d=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(d>=r)return T.error(Wl.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${d+1}`);d=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return T.error(Wl.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return T.error(Wl.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:dh(c)})}}return T.ok(i)}(e.guarantees,t,e.slot,(t,r)=>this.getGuarantorAssignment(t,r,e.newEntropy))}verifyPostSignatureChecks(e){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return T.error(Wl.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return T.error(Wl.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${o}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return T.error(Wl.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return T.error(Wl.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const a=ae(...e.results.map(e=>e.gas));if(a.overflow||a.value>gh)return T.error(Wl.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${gh}`)}return T.ok(_)}(e,this.state.availabilityAssignment,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=dt.new(),o=gt.new(),a=gt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=Fr.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),o.insertAll(e.report.context.prerequisites),a.insertAll(e.report.segmentRootLookup.map(e=>e.workPackageHash));for(const r of e.report.results){const e=t.getService(r.serviceId);if(null===e)return T.error(Wl.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return T.error(Wl.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return T.error(Wl.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=dt.new();for(const e of r.recentBlocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return T.error(Wl.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return T.error(Wl.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=ql.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return T.error(Wl.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return T.error(Wl.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return T.error(Wl.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return T.ok(_)}(Math.max(0,e.slot-14400),i,t,r,s);if(c.isError)return c;const l=function(e,t){const r=gt.new();for(const e of t.recentBlocks)r.insertAll(Array.from(e.reported.keys()));for(const e of t.recentlyAccumulated)r.insertAll(Array.from(e));for(const e of t.accumulationQueue)r.insertAll(e.map(e=>e.report.workPackageSpec.hash));for(const e of t.availabilityAssignment)null!==e&&r.insert(e.workReport.data.workPackageSpec.hash);const s=r.intersection(e);for(const e of s)return T.error(Wl.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return T.ok(_)}(gt.viewDictionaryKeys(n),t);if(l.isError)return l;const h=dt.new();for(const e of t.recentBlocks)for(const t of e.reported.values())h.set(t.workPackageHash,t.segmentTreeRoot);const u=function({currentWorkPackages:e,recentlyReported:t,prerequisiteHashes:r,segmentRootLookupHashes:s}){const i=(r,s=!1)=>{for(const i of r)if(!e.has(i)&&!t.has(i))return T.error(s?Wl.SegmentRootLookupInvalid:Wl.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return T.ok(_)},n=i(r);if(n.isError)return n;const o=i(s,!0);return o.isError?o:T.ok(_)}({currentWorkPackages:n,recentlyReported:h,prerequisiteHashes:o,segmentRootLookupHashes:a});if(u.isError)return u;for(const t of e.guarantees){const e=t.materialize().report;for(const t of e.segmentRootLookup){let e=n.get(t.workPackageHash);if(void 0===e){const r=h.get(t.workPackageHash);e=void 0!==r?Fr.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return T.error(Wl.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return T.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return T.ok(_);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return T.error(Wl.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=hh(e,i),o=hh(t,i),a=Math.max(0,n-1)*i;if(t>e)return T.error(Wl.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<a)return T.error(Wl.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,h=e;n>o&&(h=Ar(e-i),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(h,e,s)&&(c=this.state.entropy[3],l=this.state.previousValidatorData));const u=lh(this.chainSpec,c,h);return T.ok((d=l,g=(e,t)=>({core:e,ed25519:t.ed25519}),u.map((e,t)=>g(e,d[t]))));var d,g}}class ph{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getStatistics(e){if(Math.floor(this.state.timeslot/this.chainSpec.epochLength)===Math.floor(e/this.chainSpec.epochLength))return this.state.statistics;const t=Cr(Array.from({length:this.chainSpec.validatorsCount},()=>Ti.empty()),this.chainSpec);return Li.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return se(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),se(t)}calculateRefineScore(e){const t={gasUsed:0n,imported:0,extrinsicCount:0,extrinsicSize:0,exported:0};for(const r of e)t.gasUsed+=r.load.gasUsed,t.imported+=r.load.importedSegments,t.extrinsicCount+=r.load.extrinsicCount,t.extrinsicSize+=r.load.extrinsicSize,t.exported+=r.load.exportedSegments;return{gasUsed:wr(t.gasUsed),exported:te(t.exported),imported:te(t.imported),extrinsicCount:te(t.extrinsicCount),extrinsicSize:se(t.extrinsicSize)}}calculateProvidedScoreService(e){const t={count:0,size:0};for(const r of e)t.count+=1,t.size+=r.blob.length;return{count:te(t.count),size:se(t.size)}}collectServiceIds(e,t,r,s){const i=new Set;for(const t of e)i.add(t.requester);for(const e of t)i.add(e.serviceId);for(const e of r)i.add(e);for(const e of s)i.add(e);return i}transition(e){const{slot:t,authorIndex:r,extrinsic:s,incomingReports:i,availableReports:n}=e,o=this.getStatistics(t),{current:a,cores:c,services:l}=o;I(void 0!==a[r],"authorIndex is out of bounds");const h=a[r].blocks+1;a[r].blocks=se(h);const u=a[r].tickets+s.tickets.length;a[r].tickets=se(u);const d=a[r].preImages+s.preimages.length;a[r].preImages=se(d);const g=s.preimages.reduce((e,t)=>e+t.blob.length,0),f=a[r].preImagesSize+g;a[r].preImagesSize=se(f);for(const{credentials:e}of s.guarantees)for(const{validatorIndex:t}of e){const e=a[t].guarantees+1;a[t].guarantees=se(e)}for(const{validatorIndex:e}of s.assurances){const t=a[e].assurances+1;a[e].assurances=se(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Sr(e),r=i.find(e=>e.coreIndex===t),{imported:o,extrinsicCount:a,extrinsicSize:l,exported:h,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:te(0),extrinsicCount:te(0),extrinsicSize:se(0),exported:te(0),gasUsed:wr(0n)},d=n.find(e=>e.coreIndex===t),g=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=o,c[t].extrinsicCount=a,c[t].extrinsicSize=l,c[t].exports=h,c[t].gasUsed=u,c[t].bundleSize=se(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(d),c[t].popularity=te(g)}l.clear();const p=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of p){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:o,extrinsicCount:a,extrinsicSize:c,exported:h}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:d,size:g}=this.calculateProvidedScoreService(u),{count:f,gasUsed:p}=e.accumulationStatistics.get(t)??{count:se(0),gasUsed:wr(0n)},{count:y,gasUsed:m}=e.transferStatistics.get(t)??{count:se(0),gasUsed:wr(0n)},b=Pi.empty();b.refinementCount=se(r.length),b.refinementGasUsed=n,b.imports=o,b.extrinsicCount=a,b.extrinsicSize=c,b.exports=h,b.providedCount=d,b.providedSize=g,b.providedCount=d,b.providedSize=g,b.accumulateCount=f,b.accumulateGasUsed=p,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class yh{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var mh;!function(e){e[e.Assurances=0]="Assurances",e[e.Disputes=1]="Disputes",e[e.Safrole=2]="Safrole",e[e.Reports=3]="Reports",e[e.Preimages=4]="Preimages",e[e.SafroleSeal=5]="SafroleSeal",e[e.Accumulate=6]="Accumulate",e[e.DeferredTransfers=7]="DeferredTransfers"}(mh||(mh={}));const bh=(e,t)=>T.taggedError(mh,e,t);class Ah{chainSpec;state;hasher;safrole;safroleSeal;disputes;reports;assurances;accumulate;deferredTransfers;preimages;recentHistory;authorization;statistics;constructor(e,t,r,s,{enableParallelSealVerification:i}){this.chainSpec=e,this.state=t,this.hasher=s;const n=zc.new({synchronous:!i});this.statistics=new ph(e,t),this.safrole=new sl(e,t,n),this.safroleSeal=new il(n),this.recentHistory=new ch(s,t),this.disputes=new Uc(e,t),this.reports=new fh(e,t,s,new yh(r)),this.assurances=new Fl(e,t),this.accumulate=new oh(e,t),this.deferredTransfers=new Dl(e,t),this.preimages=new Ic(t),this.authorization=new ah(e,t)}async verifySeal(e,t){const r=this.safrole.getSafroleSealState(e);return await this.safroleSeal.verifyHeaderSeal(t.header.view(),r)}async transition(e,t,r=null,s=!1){const i=e.header.materialize(),n=i.timeSlotIndex;let o=r;if(s&&(o=Ge(i.seal).asOpaque()),null===o){const t=await this.verifySeal(n,e);if(t.isError)return bh(mh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return bh(mh.Disputes,a);const{disputesRecords:c,availabilityAssignment:l,...h}=a.ok.stateUpdate;S(h);const u=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize(),punishSet:c.punishSet});if(u.isError)return bh(mh.Safrole,u);const{timeslot:d,ticketsAccumulator:g,sealingKeySeries:f,epochRoot:p,entropy:y,nextValidatorData:m,currentValidatorData:b,previousValidatorData:A,...I}=u.ok.stateUpdate;S(I);const v=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),newEntropy:y});if(v.isError)return bh(mh.Reports,v);const{availabilityAssignment:w,...E}=v.ok.stateUpdate;S(E);const C=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(C.isError)return bh(mh.Assurances,C);const{availabilityAssignment:k,...x}=C.ok.stateUpdate;S(x);const B=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(B.isError)return bh(mh.Preimages,B);const{preimages:_,...R}=B.ok;S(R);const O=await this.accumulate.transition({slot:n,reports:C.ok.availableReports,entropy:y[0]});if(O.isError)return bh(mh.Accumulate,O);const{root:U,stateUpdate:N,accumulationStatistics:D,pendingTransfers:M,...P}=O.ok;S(P);const{privilegedServices:L,authQueues:H,designatedValidatorData:K,timeslot:V,preimages:Q,...F}=N,G=await this.deferredTransfers.transition({pendingTransfers:M,servicesUpdate:{...F,preimages:Q},timeslot:n});if(G.isError)return bh(mh.DeferredTransfers,G);const{servicesUpdate:$,transferStatistics:j,...q}=G.ok;S(q);const z=this.recentHistory.transition({headerHash:t,priorStateRoot:i.priorStateRoot,accumulateRoot:U,workPackages:v.ok.reported}),{recentBlocks:W,...J}=z;S(J);const Y=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:X,...Z}=Y;S(Z);const ee=e.extrinsic.materialize(),te=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:ee,incomingReports:ee.guarantees.map(e=>e.report),availableReports:C.ok.availableReports,accumulationStatistics:D,transferStatistics:j}),{statistics:re,...se}=te;return S(se),T.ok({...void 0!==H?{authQueues:H}:{},...void 0!==K?{designatedValidatorData:K}:{},...void 0!==L?{privilegedServices:L}:{},authPools:X,preimages:_.concat(Q),disputesRecords:c,availabilityAssignment:Ih(this.state.availabilityAssignment,w,l,k),recentBlocks:W,statistics:re,timeslot:d,epochRoot:p,entropy:y,currentValidatorData:b,nextValidatorData:m,previousValidatorData:A,sealingKeySeries:f,ticketsAccumulator:g,...F})}getUsedAuthorizerHashes(e){const t=new Map;for(const r of e){const e=r.view().report.view(),s=e.coreIndex.materialize(),i=t.get(s)??gt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}function Ih(e,t,r,s){const i=e.slice();for(const n of t.keys())null!==r[n]&&null!==s[n]||(i[n]=null),null!==t[n]&&e[n]!==t[n]&&(i[n]=t[n]);return i}var vh;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(vh||(vh={}));const wh=(e,t)=>T.taggedError(vh,e,t);class Sh{logger;blocks;states;verifier;stf;state;constructor(e,t,r,s,i){this.logger=r,this.blocks=s,this.states=i;const n=this.blocks.getBestHeaderHash(),o=i.getState(n);if(null===o)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new Sc(t,s),this.stf=new Ah(e,o,s,t,{enableParallelSealVerification:!0}),this.state=o,r.info(`😎 Best time slot: ${o.timeslot} (header hash: ${n})`)}async preverifySeal(e,t){try{const r=await this.stf.verifySeal(e,t);return r.isOk?r.ok:(this.logger.warn(`Unable to pre-verify the seal: ${U(r)}`),null)}catch(e){return this.logger.warn(`Error while trying to pre-verify the seal: ${e}`),null}}async importBlock(e,t,r=!1){const s=this.logger;s.log("🧱 Attempting to import a new block "+(null!==t?"(seal preverified)":""));const i=C("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return wh(vh.Verifier,n);const o=e.header.view().timeSlotIndex.materialize(),a=n.ok;s.log(`🧱 Verified block: Got hash ${a} for block at slot ${o}.`);const c=C("import:stf"),l=await this.stf.transition(e,a,t,r);if(s.log(c()),l.isError)return wh(vh.Stf,l);const h=l.ok,u=C("import:state"),d=await this.states.updateAndSetState(a,this.state,h);if(d.isError)return s.error(`🧱 Unable to update state: ${U(d)}`),wh(vh.Update,d);const g=this.states.getState(a);if(null===g)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(g.backend),s.log(u());const f=C("import:db"),p=this.blocks.insertBlock(new Me(a,e)),y=await this.states.getStateRoot(g);s.log(`🧱 Storing post-state-root for ${a}: ${y}.`);const m=this.blocks.setPostStateRoot(a,y);return await Promise.all([p,m]),s.log(f()),await this.blocks.setBestHeaderHash(a),T.ok(new Me(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const Eh=Js.new(void 0,"importer");class Ch extends Pn{onBestBlock=new Nn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{bestBlock:e=>this.triggerBestBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}triggerBestBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ue.decodeObject(es,e,t.chainSpec);this.onBestBlock.emit(r)}}sendBlock(e,t){e.sendSignal("block",t,[t.buffer])}finish(e){return this.onBestBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class kh extends Pn{onBlock=new Nn;constructor(){super({name:"ready(importer)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{block:e=>this.triggerOnBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}announce(e,t){const r=this.getConfig(),s=me.encodeObject(es,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ue.decodeObject(is.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else Eh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}async endWork(){return this.onBlock.markDone(),{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const xh=Js.new(void 0,"importer");if(!Ys.isMainThread){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e=function(){const e=new Kn("ready(importer)",wt.reInit),t=new kh,r=new Ln;return new Dn("importer",e,[e,t,r])}();On.receiveChannel(e,Ys.parentPort).then(e=>async function(e){xh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{xh.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new si(r.dbPath),i=new Zs(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=new Sh(r.chainSpec,new Ac(r.chainSpec,await Bh,new Le),xh,i,n);let a=!1;const c=new vc(r.chainSpec,o);e.onBlock.on(async s=>{const i=c.push(s)??Ar(0);if(xh.log(`🧊 Got block: #${i}`),!a){a=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:a}=s,l=C("importBlock"),h=await o.importBlock(i,await n,r.omitSealVerification);if(h.isOk){const r=h.ok;e.announce(t,r),xh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else xh.log(`❌ Rejected block #${a}: ${U(h)}`);xh.log(l())}}finally{a=!1}}})});xh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>xh.error(e))}const Bh=ht.create(),_h=t(import.meta.url)("node:timers/promises");class Rh{chainSpec;keccakHasher;blocks;states;hashAllocator=new Le;lastHeaderHash;lastHeader;lastState;constructor(e,t,r,s){this.chainSpec=e,this.keccakHasher=t,this.blocks=r,this.states=s;const{lastHeaderHash:i,lastHeader:n,lastState:o}=Rh.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=Rh.getLastHeaderAndState(this.blocks,this.states);this.lastHeaderHash=e,this.lastHeader=t,this.lastState=r}static getLastHeaderAndState(e,t){const r=e.getBestHeaderHash(),s=e.getHeader(r)?.materialize()??null,i=t.getState(r);if(null===s)throw new Error(`Missing best header: ${r}! Make sure DB is initialized.`);if(null===i)throw new Error(`Missing last state at ${r}! Make sure DB is initialized.`);return{lastHeaderHash:r,lastHeader:s,lastState:i}}async nextEncodedBlock(){const e=await this.nextBlock();return me.encodeObject(is.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Ir(e%6),r=new Ac(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=ss.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:br.create({verdicts:[],culprits:[],faults:[]})}),o=me.encodeObject(ss.Codec,n,this.chainSpec),a=ue.decodeObject(ss.Codec.View,o,this.chainSpec),c=r.extrinsic(a).hash,l=me.create();l.i32(e),l.i16(t),l.bytes(M.fill(90,0));const h=M.fromBlob(l.viewResult().raw,96),u=Xr.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Ar(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:M.fill(96,42*e%256).asOpaque(),seal:h.asOpaque()}),d=me.encodeObject(Xr.Codec,u,this.chainSpec),g=ue.decodeObject(Xr.Codec.View,d,this.chainSpec);return this.lastHeaderHash=r.header(g).hash,this.lastHeader=u,is.create({header:u,extrinsic:n})}}const Oh=Js.new(void 0,"block-generator");class Uh extends Pn{onBlock=new Nn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):Oh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}finish(e){return this.onBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class Th extends Pn{constructor(){super({name:"ready(generator)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()}})}sendBlock(e,t){e.sendSignal("block",t.raw,[t.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Config not received.");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const Nh=Js.new(void 0,"block-generator");if(!Ys.isMainThread){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e=function(){const e=new Kn("ready(generator)",wt.reInit),t=new Th,r=new Ln;return new Dn("block-generator",e,[e,t,r])}();On.receiveChannel(e,Ys.parentPort).then(e=>async function(e){Nh.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new si(r.dbPath),i=new Zs(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=await t.doUntil("finished",async(e,t,s)=>{let o=0;const a=new Rh(r.chainSpec,await ht.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();Nh.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,_h.setTimeout)(3e3)}});Nh.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{Nh.error(e),void 0!==e.stack&&Nh.error(e.stack),void 0!==e.cause&&Nh.error(e.cause)})}const Dh=t(import.meta.url)("dgram");var Mh,Ph;(Ph=Mh||(Mh={}))[Ph.NOTSET=0]="NOTSET",Ph[Ph.DEBUG=1]="DEBUG",Ph[Ph.INFO=2]="INFO",Ph[Ph.WARN=3]="WARN",Ph[Ph.ERROR=4]="ERROR",Ph[Ph.SILENT=100]="SILENT";const Lh="captureStackTrace"in Error,Hh="stackTraceLimit"in Error;function Kh(e){switch(e){case Mh.NOTSET:return"NOTSET";case Mh.DEBUG:return"DEBUG";case Mh.INFO:return"INFO";case Mh.WARN:return"WARN";case Mh.ERROR:return"ERROR";case Mh.SILENT:return"SILENT"}}function Vh(e,t){return"function"==typeof t?t():t}function Qh(e){return JSON.stringify(e,Vh)}const Fh=Symbol("level"),Gh=Symbol("key"),$h=Symbol("keys"),jh=Symbol("date"),qh=Symbol("msg"),zh=Symbol("stack"),Wh=Symbol("data"),Jh=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Gh)s+=r.key;else if(n===$h)s+=r.keys;else if(n===jh)s+=r.date().toISOString();else if(n===qh)null!=r.msg&&(s+=r.msg);else if(n===Fh)s+=Kh(r.level);else if(n===Wh)s+=Qh(r.data);else if(n===zh){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${Fh}:${Gh}:${qh}`,Yh=class{formatter;constructor(e=Jh){this.formatter=e}setFormatter(e){this.formatter=e}handle(e,t){const r=null!=t?t(e):this.format(e);this.emit(r)}format(e){return this.formatter(e)}},Xh=class extends Yh{emit(e){console.error(e)}};class Zh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Mh.NOTSET,r=[new Xh],s){this.key=e,this.level=t,this.handlers=new Set(r),this.parent=s,this.keys=null!=s?`${s.keys}.${e}`:e,this.loggersRegistry=new FinalizationRegistry(e=>{this._loggers.delete(e)})}get loggers(){return new Map([...this._loggers.entries()].map(([e,t])=>{const r=t.deref();return null!=r?[e,r]:void 0}).filter(e=>null!=e))}getChild(e){let t=this._loggers.get(e),r=t?.deref();return null!=r||(r=new Zh(e,Mh.NOTSET,[],this),t=new WeakRef(r),this._loggers.set(e,t),this.loggersRegistry.register(r,e)),r}getParent(){return this.parent}setLevel(e){this.level=e}getEffectiveLevel(){return this.level!==Mh.NOTSET?this.level:this.parent?this.parent.getEffectiveLevel():this.level}isEnabledFor(e){return e>=this.level}addHandler(e){this.handlers.add(e)}removeHandler(e){this.handlers.delete(e)}clearHandlers(){this.handlers.clear()}hasHandlers(){return!!this.handlers.size||(this.parent?.hasHandlers()??!1)}setFilter(e){this.filter=e}unsetFilter(){delete this.filter}debug(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Mh.DEBUG,t):this.log(e,t,Mh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Mh.INFO,t):this.log(e,t,Mh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Mh.WARN,t):this.log(e,t,Mh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Mh.ERROR,t):this.log(e,t,Mh.ERROR,r)}log(e,t,r,s){if(r<this.getEffectiveLevel())return;const i=this.makeRecord(e,t,r);this.callHandlers(i,r,s)}makeRecord(e,t,r){return{logger:this,key:this.key,keys:this.keys,level:r,msg:e?.toString(),data:t,date:()=>new Date,stack:()=>{let e;if(Lh&&Hh){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,Zh.prototype.log),Error.stackTraceLimit--,e=t.stack,e=e.slice(e.indexOf("\n",e.indexOf("\n")+1)+1)}else e=(new Error).stack??"",e=e.slice(e.indexOf("\n")+1);return e}}}callHandlers(e,t,r,s=""){if(!(t<this.getEffectiveLevel())&&(s=`${this.key}.${s}`,null==this.filter||this.filter.test(s))){for(const t of this.handlers)t.handle(e,r);this.parent&&this.parent.callHandlers(e,t,r,s)}}}const eu=Zh;t(import.meta.url)("node:process");class tu extends Event{detail;constructorParams;constructor(e=new.target.name,t,r){"string"==typeof e?(super(e,t),this.detail=t?.detail):(super(new.target.name,e),this.detail=e.detail,r=t),this.constructorParams=r??arguments}clone(){try{return new this.constructor(...this.constructorParams)}catch(e){if("TypeError"===e.name)throw new TypeError(`Cloning ${this.constructor.name} requires the original constructor arguments to be passed into super`);throw e}}}const ru=tu;class su extends ru{constructor(e){super(su.name,e,arguments)}}const iu=su;class nu extends ru{constructor(e){super(nu.name,e,arguments)}}const ou=nu;class au extends ru{constructor(e){super(au.name,e,arguments)}}const cu=au,lu=Symbol("_eventTarget"),hu=Symbol("eventTarget"),uu=Symbol("_eventHandlers"),du=Symbol("eventHandlers"),gu=Symbol("_eventHandled"),fu=Symbol("eventHandled"),pu=Symbol("_handleEventError"),yu=Symbol("handleEventError");function mu(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function bu(e,t){return e.capture===t.capture}function Au(){return e=>{const t=class extends e{[lu]=new EventTarget;[uu]=new Map;[gu]=new WeakSet;[pu]=e=>{throw e.detail};constructor(...e){super(...e),this[lu].addEventListener(cu.name,this[pu])}get[hu](){return this[lu]}get[du](){return this[uu]}get[fu](){return this[gu]}get[yu](){return this[pu]}addEventListener(e,t,r){r=mu(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[uu].get(e),void 0===n&&(n=new Set,this[uu].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,bu(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[gu].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new cu({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new cu({detail:e}))}},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[gu].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new cu({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new cu({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[lu].addEventListener(e,i,r),e===cu.name&&1===n?.size&&this[lu].removeEventListener(cu.name,this[pu])}removeEventListener(e,t,r){let s,i,n;if(r=mu(r),null!=t){if(i=this[uu].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&bu(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[lu].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===cu.name&&0===i.size&&this[lu].addEventListener(cu.name,this[pu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof cu)return this[lu].dispatchEvent(e);{let t=this[lu].dispatchEvent(e);if(t&&!this[gu].has(e)){const r=new iu({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[lu].dispatchEvent(r)}if(t){const r=new ou({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[lu].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function Iu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return await t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}async function*vu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return yield*t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}class wu extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof wu?e:super.resolve(e)}static reject(e){return super.reject(e)}static all(e,t){const r=super.all(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static allSettled(e,t){const r=super.allSettled(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static race(e,t){const r=super.race(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static any(e,t){const r=super.any(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static from(e,t){return new this((t,r)=>{e.then(t,r)},t)}reject;abortController;constructor(e,t){let r,s,i,n;"function"==typeof t?(r=new AbortController,t(r.signal),s=r.signal,i=!0):null!=t?(r=t,s=t.signal,i=!0):(r=new AbortController,s=new Proxy(r.signal,{get:(e,t,r)=>"addEventListener"===t?function(...r){return i=!0,e[t].apply(this,r)}:Reflect.get(e,t,r),set:(e,t,r)=>("onabort"===t&&(i=!0),Reflect.set(e,t,r)),deleteProperty:(e,t)=>("onabort"===t&&(i=!0),Reflect.deleteProperty(e,t))}),i=!1),super((t,r)=>{n=e=>{e instanceof DOMException&&"AbortError"===e.name&&(e=void 0),r(e)},e(t,n,s)}),i||r.signal.addEventListener("abort",()=>{n(r.signal.reason)},{once:!0}),this.reject=n,this.abortController=r}get[Symbol.toStringTag](){return this.constructor.name}cancel(e){this.abortController.abort(e)}then(e,t,r){let s,i,n;"function"==typeof e&&(i=t=>e(t,s)),"function"==typeof t&&(n=e=>t(e,s));const o=super.then(i,n),a=wu.from(o,r);return s=a.abortController.signal,a}catch(e,t){let r,s;"function"==typeof e&&(s=t=>e(t,r));const i=super.catch(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}finally(e,t){let r,s;"function"==typeof e&&(s=()=>e(r));const i=super.finally(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}}const Su=wu,Eu=t(import.meta.url)("node:perf_hooks");var Cu,ku=(Cu=function(e,t){return Cu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Cu(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Cu(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),xu=function(e){function t(t){var r,s,i,n=this.constructor,o=e.call(this,t)||this;return Object.defineProperty(o,"name",{value:n.name,enumerable:!1,configurable:!0}),r=o,s=n.prototype,(i=Object.setPrototypeOf)?i(r,s):r.__proto__=s,function(e,t){void 0===t&&(t=e.constructor);var r=Error.captureStackTrace;r&&r(e,t)}(o),o}return ku(t,e),t}(Error);const Bu=class extends xu{static description="";static fromJSON(e){if("object"!=typeof e||e.type!==this.name||"object"!=typeof e.data||"string"!=typeof e.data.message||isNaN(Date.parse(e.data.timestamp))||"object"!=typeof e.data.data||"stack"in e.data&&"string"!=typeof e.data.stack)throw new TypeError(`Cannot decode JSON to ${this.name}`);const t=new this(e.data.message,{timestamp:new Date(e.data.timestamp),data:e.data.data,cause:e.data.cause});return t.stack=e.data.stack,t}data;cause;timestamp;constructor(e="",t={}){super(e),this.timestamp=t.timestamp??new Date(Eu.performance.timeOrigin+Eu.performance.now()),this.data=t.data??{},this.cause=t.cause}get description(){return this.constructor.description}toJSON(){return{type:this.constructor.name,description:this.description,data:{message:this.message,timestamp:this.timestamp,data:this.data,cause:this.cause,stack:this.stack}}}};function _u(e,t,r=new Set){if(r.has(e))return!1;if(r.add(e),t(e))return!0;if(e instanceof AggregateError){for(const s of e.errors){const e=_u(s,t,r);if(e)return e}return _u(e.cause,t,r)}return e instanceof Error&&_u(e.cause,t,r)}class Ru extends Bu{static description="Timer error"}class Ou extends Ru{static description="The timer has already ended"}class Uu{_delay;lazy;timestamp;_scheduled;handler;p;resolveP;rejectP;abortController;timeoutRef;_status=null;constructor(e,t=0,r=!1,s){let i,n;"function"==typeof e?i=e:"object"==typeof e&&null!==e&&(i=e.handler,t=e.delay??t,r=e.lazy??r,s=e.controller??s),isNaN(t)?t=0:(t=Math.max(t,0),isFinite(t)&&(t=Math.min(t,2**31-1))),this.handler=i,this._delay=t,this.lazy=r,"function"==typeof s?(n=new AbortController,s(n.signal)):null!=s?n=s:(n=new AbortController,n.signal.addEventListener("abort",()=>{this.reject(n.signal.reason)})),this.p=new Su((e,t)=>{this.resolveP=e.bind(this.p),this.rejectP=t.bind(this.p)},n),this.abortController=n,isFinite(t)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},t),this.timestamp=new Date(Eu.performance.timeOrigin+Eu.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(Eu.performance.timeOrigin+Eu.performance.now()))}get[Symbol.toStringTag](){return this.constructor.name}get status(){return this._status}get scheduled(){return this._scheduled}get delay(){return this._delay}getTimeout(){return null!==this._status?0:null==this._scheduled?1/0:Math.max(Math.trunc(this._scheduled.getTime()-(Eu.performance.timeOrigin+Eu.performance.now())),0)}toString(){return this.getTimeout().toString()}valueOf(){return this.getTimeout()}cancel(e){this.p.catch(()=>{}),this.p.cancel(e)}then(e,t,r){return this.p.then(e,t,r)}catch(e,t){return this.p.catch(e,t)}finally(e,t){return this.p.finally(e,t)}refresh(){if(null!=this._status)throw new Ou;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Ou;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(Eu.performance.timeOrigin+Eu.performance.now()+e)):(this.timeoutRef=setInterval(()=>{},2**31-1),delete this._scheduled)}async fulfill(){if(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,null!=this.handler)try{const e=await this.handler(this.abortController.signal);this.resolveP(e)}catch(e){this.rejectP(e)}else this.resolveP();delete this.handler,this._status="settled"}async reject(e){this.lazy&&"settling"===this._status||"settled"===this._status||(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,this.rejectP(e),delete this.handler,this._status="settled")}}const Tu=Uu;function Nu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Du(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new Tu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Tu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new Tu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new Su((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}class Mu extends Bu{static description="Async locks error"}class Pu extends Mu{static description="Async locks timeout"}const Lu=class{limit;priority;_count=0;currentWeight=0;queue=[];abortQueueMap=new WeakMap;constructor(e,t=!1){if(e<1)throw new RangeError("Semaphore must be constructed with `limit` >= 1");this.limit=e,this.priority=t}get count(){return this._count}isLocked(){return this._count>0}lock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},()=>Du((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=Nu();if(e.signal.aborted)return this._count--,i(e.signal.reason),r;const n=()=>{this._count--;const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)};let o=!1;const a={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{o||(o=!0,this._count--,this.currentWeight-=t,this.processQueue())},this])},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,Pu,r,[t])}waitForUnlock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},Du((e,t)=>{const{p:r,resolveP:s,rejectP:i}=Nu();if(e.signal.aborted)return i(e.signal.reason),r;const n=()=>{const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)},o={task:()=>{e.signal.removeEventListener("abort",n),s()},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,Pu,r,[t])}withF(...e){const t=e.pop();return Iu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return vu([this.lock(...e)],([e])=>t(e))}insertQueue(e){if(this.priority){let t=this.queue.length;for(;t>0&&this.queue[t-1].weight<e.weight;)t--;this.queue.splice(t,0,e)}else this.queue.unshift(e)}processQueue(){for(;this.queue.length>0&&this.currentWeight+this.queue[this.queue.length-1].weight<=this.limit;){const e=this.queue.pop();e.aborted||e.task()}}},Hu=class{semaphore=new Lu(1);get count(){return this.semaphore.count}isLocked(){return this.semaphore.isLocked()}lock(e){const t=this.semaphore.lock(1,e);return()=>{const e=t();return e.then(([e])=>[e,this],void 0,t=>{t.addEventListener("abort",()=>{e.cancel(t.reason)},{once:!0})})}}waitForUnlock(e){return this.semaphore.waitForUnlock(1,e)}withF(...e){const t=e.pop();return Iu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return vu([this.lock(...e)],([e])=>t(e))}},Ku=class{readersLock=new Hu;writersLock=new Hu;readersRelease;readerCountBlocked=0;acquireReadersLockP;_readerCount=0;_writerCount=0;get count(){return this.readerCount+this.writerCount}get readerCount(){return this._readerCount+this.readerCountBlocked}get writerCount(){return this._writerCount}isLocked(e){return"read"===e?0===this._writerCount&&this.readersLock.isLocked():"write"===e?this.writersLock.isLocked():this.readersLock.isLocked()||this.writersLock.isLocked()}lock(...e){const t=(2===e.length||"string"==typeof e[0]?e[0]:void 0)??"write",r=2===e.length?e[1]:"string"!=typeof e[0]?e[0]:void 0;switch(t){case"read":return this.read(r);case"write":return this.write(r)}}read(e){return e=null!=e?{...e}:{},()=>Du(async e=>{if(this._writerCount>0){++this.readerCountBlocked;const t=this.writersLock.waitForUnlock(e);try{await t}finally{--this.readerCountBlocked}}if(1===++this._readerCount){const t=this.readersLock.lock(e);this.acquireReadersLockP=t();try{[this.readersRelease]=await this.acquireReadersLockP}catch(e){throw--this._readerCount,e}}else await this.acquireReadersLockP.catch(()=>{});let t=!1;return[async()=>{t||(t=!0,0===--this._readerCount&&await this.readersRelease())},this]},!0,1/0,Pu,e,[])}write(e){return e=null!=e?{...e}:{},()=>Du(async e=>{++this._writerCount;const t=this.writersLock.lock(e)();let r;try{[r]=await t}catch(e){throw--this._writerCount,e}const s=this.readersLock.lock(e)();try{[this.readersRelease]=await s}catch(e){throw await r(),--this._writerCount,e}let i=!1;return[async()=>{i||(i=!0,await this.readersRelease(),await r(),--this._writerCount)},this]},!0,1/0,Pu,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return Su.all([t,r]).then(()=>{},void 0,e=>{e.addEventListener("abort",()=>{t.cancel(e.reason),r.cancel(e.reason)},{once:!0})})}withF(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadF(...e);case"write":return this.withWriteF(...e)}}withReadF(...e){const t=e.pop();return Iu([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return Iu([this.write(...e)],([e])=>t(e))}withG(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadG(...e);case"write":return this.withWriteG(...e)}}withReadG(...e){const t=e.pop();return vu([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return vu([this.write(...e)],([e])=>t(e))}},Vu=Symbol("_running"),Qu=Symbol("running"),Fu=Symbol("_destroyed"),Gu=Symbol("destroyed"),$u=Symbol("_status"),ju=Symbol("status"),qu=Symbol("_statusP"),zu=Symbol("statusP"),Wu=Symbol("resolveStatusP"),Ju=Symbol("initLock"),Yu=(async()=>{}).constructor,Xu=function*(){}.constructor,Zu=async function*(){}.constructor,ed="captureStackTrace"in Error;function td(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function rd(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);ed?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class sd extends ru{}class id extends sd{}class nd extends sd{}class od extends sd{}class ad extends sd{}class cd extends sd{}class ld extends sd{}class hd extends Bu{static description="Async init error"}class ud extends hd{static description="Async init is not running"}class dd extends hd{static description="Async init is destroyed"}function gd({eventDestroy:e=cd,eventDestroyed:t=ld}={}){return r=>{const{p:s,resolveP:i}=td(),n=class extends(Au()(r)){[Fu]=!1;[$u]=null;[qu]=s;[Wu]=i;[Ju]=new Ku;get[Gu](){return this[Fu]}get[ju](){return this[$u]}get[zu](){return this[qu]}async destroy(...r){return this[Ju].withWriteF(async()=>{if(this[Fu])return;this[$u]="destroying",this[Wu]("destroying");const{p:s,resolveP:i}=td();let n;return this[qu]=s,this[Wu]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[Fu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[$u]=null,this[Wu](null);const{p:e,resolveP:t}=td();this[qu]=e,this[Wu]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function fd(e=new dd,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof Yu?async function(...s){if(this[Ju].isLocked("write")&&null===this[$u]&&await this[qu],r.includes(this[$u]))return a.apply(this,s);if(t)return this[Ju].withReadF(async()=>{if(this[Fu])throw rd(e,n[o]),e;return a.apply(this,s)});if(this[Ju].isLocked("write")||this[Fu])throw rd(e,n[o]),e;return a.apply(this,s)}:a instanceof Xu?function*(...t){if(r.includes(this[$u]))return yield*a.apply(this,t);if(this[Ju].isLocked("write")&&null!==this[ju]||this[Fu])throw rd(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Zu?async function*(...s){if(this[Ju].isLocked("write")&&null===this[$u]&&await this[qu],r.includes(this[$u]))return yield*a.apply(this,s);if(t)return yield*this[Ju].withReadG(()=>{if(this[Fu])throw rd(e,n[o]),e;return a.apply(this,s)});if(this[Ju].isLocked("write")||this[Fu])throw rd(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[$u]))return a.apply(this,t);if(this[Ju].isLocked("write")&&null!==this[ju]||this[Fu])throw rd(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function pd({eventStart:e=id,eventStarted:t=nd,eventStop:r=od,eventStopped:s=ad}={}){return i=>{const{p:n,resolveP:o}=td(),a=class extends(Au()(i)){[Vu]=!1;[$u]=null;[qu]=n;[Wu]=o;[Ju]=new Ku;get[Qu](){return this[Vu]}get[ju](){return this[$u]}get[zu](){return this[qu]}async start(...r){return this[Ju].withWriteF(async()=>{if(this[Vu])return;this[$u]="starting",this[Wu]("starting");const{p:s,resolveP:i}=td();let n;return this[qu]=s,this[Wu]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[Vu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[$u]=null,this[Wu](null);const{p:e,resolveP:t}=td();this[qu]=e,this[Wu]=t})}async stop(...e){return this[Ju].withWriteF(async()=>{if(!this[Vu])return;this[$u]="stopping",this[Wu]("stopping");const{p:t,resolveP:i}=td();let n;return this[qu]=t,this[Wu]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[Vu]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[$u]=null,this[Wu](null);const{p:e,resolveP:t}=td();this[qu]=e,this[Wu]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function yd(e=new ud,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof Yu?async function(...s){if(this[Ju].isLocked("write")&&null===this[$u]&&await this[qu],r.includes(this[$u]))return a.apply(this,s);if(t)return this[Ju].withReadF(async()=>{if(!this[Vu])throw rd(e,n[o]),e;return a.apply(this,s)});if(this[Ju].isLocked("write")||!this[Vu])throw rd(e,n[o]),e;return a.apply(this,s)}:a instanceof Xu?function*(...t){if(r.includes(this[$u]))return yield*a.apply(this,t);if(this[Ju].isLocked("write")&&null!==this[ju]||!this[Vu])throw rd(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Zu?async function*(...s){if(this[Ju].isLocked("write")&&null===this[$u]&&await this[qu],r.includes(this[$u]))return yield*a.apply(this,s);if(t)return yield*this[Ju].withReadG(()=>{if(!this[Vu])throw rd(e,n[o]),e;return a.apply(this,s)});if(this[Ju].isLocked("write")||!this[Vu])throw rd(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[$u]))return a.apply(this,t);if(this[Ju].isLocked("write")&&null!==this[ju]||!this[Vu])throw rd(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class md extends Uint8Array{string;static fromString(e){const t=Buffer.from(e,"hex");return new this(t.buffer,t.byteOffset,t.byteLength)}static fromBuffer(e){return new this(e.buffer,e.byteOffset,e.byteLength)}constructor(...e){super(...e),this.string=this.toBuffer().toString("hex")}toString(){return this.string}toBuffer(){return Buffer.from(this.buffer,this.byteOffset,this.byteLength)}[Symbol.toPrimitive](e){return this.toString()}}const bd=md;class Ad{[Symbol.toStringTag]="QUICConnectionMap";_serverConnections=new Map;_clientConnections=new Map;constructor(e){if(null!=e)for(const[t,r]of e)this.set(t,r)}get size(){return this._serverConnections.size+this._clientConnections.size}get serverConnections(){return this._serverConnections}get clientConnections(){return this._clientConnections}has(e){return this._serverConnections.has(e.toString())||this._clientConnections.has(e.toString())}get(e){return this._serverConnections.get(e.toString())??this._clientConnections.get(e.toString())}set(e,t){return"server"===t.type?this._serverConnections.set(e.toString(),t):"client"===t.type&&this._clientConnections.set(e.toString(),t),this}delete(e){return this._serverConnections.delete(e.toString())||this._clientConnections.delete(e.toString())}clear(){this._serverConnections.clear(),this._clientConnections.clear()}forEach(e,t){this._serverConnections.forEach((r,s)=>{e.bind(t)(r,bd.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,bd.fromString(s),this)})}[Symbol.iterator](){const e=this._serverConnections[Symbol.iterator](),t=this._clientConnections[Symbol.iterator](),r={next:()=>{const r=e.next();if(!r.done){const[e,t]=r.value;return{done:!1,value:[bd.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[bd.fromString(e),t]}}return{done:!0,value:void 0}},[Symbol.iterator]:()=>r};return r}entries(){return this[Symbol.iterator]()}keys(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[0]}},[Symbol.iterator]:()=>e};return e}values(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[1]}},[Symbol.iterator]:()=>e};return e}}const Id=Ad,vd="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",wd=t(import.meta.url)("dns");var Sd=o(618);class Ed extends Bu{static description="QUIC error"}class Cd extends Bu{static description="You should never see this error"}class kd extends Bu{static description="Host provided was not valid"}class xd extends Bu{static description="Port provided was not valid"}class Bd extends Ed{static description="QUIC config error"}class _d extends Ed{static description="QUIC Socket error"}class Rd extends _d{static description="QUIC Socket is not running"}class Od extends _d{static description="QUIC Socket has active connections"}class Ud extends _d{static description="QUIC Socket cannot bind to the specified address"}class Td extends _d{static description="QUIC Socket cannot send to the specified address"}class Nd extends _d{static description="QUIC Socket internal error"}class Dd extends Ed{static description="QUIC Client error"}class Md extends Dd{static description="QUIC Client is destroyed"}class Pd extends Dd{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Ld extends Dd{static description="QUIC Client had a failure relating to an invalid argument"}class Hd extends Dd{static description="QUIC Client cannot be created with the specified host"}class Kd extends Dd{static description="QUIC Client internal error"}class Vd extends Ed{static description="QUIC Server error"}class Qd extends Vd{static description="QUIC Server is not running"}class Fd extends Vd{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class Gd extends Vd{static description="QUIC Server creating a new connection"}class $d extends Vd{static description="QUIC Server internal error"}class jd extends Vd{static description="QUIC Server is stopping"}class qd extends Ed{static description="QUIC Connection error"}class zd extends qd{static description="QUIC Connection is stopping"}class Wd extends qd{static description="QUIC Connection is not running"}class Jd extends qd{static description="QUIC Connection cannot be restarted because it has already been closed"}class Yd extends Ed{static description="QUIC Connection start requires data when it is a server connection"}class Xd extends qd{static description="QUIC connection invalid configuration"}class Zd extends qd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class eg extends Zd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class tg extends qd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class rg extends Zd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class sg extends qd{static description="QUIC Connection max idle timeout exhausted"}class ig extends qd{static description="QUIC Connection internal error"}class ng extends Ed{static description="QUIC Stream error"}class og extends ng{static description="QUIC Stream is destroyed"}class ag extends ng{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class cg extends ng{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class lg extends ng{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class hg extends ng{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class ug extends ng{static description="QUIC Stream internal error"}class dg extends ng{static description="QUIC Stream limit has been reached"}const gg=new TextEncoder,fg=new TextDecoder("utf-8");function pg(e){throw new Cd(e)}function yg(e){return function(...t){return new Promise((r,s)=>{t.push((e,...t)=>{if(null!=e)return s(e);0===t.length?r():1===t.length?r(t[0]):r(t)}),e.apply(this,t)})}}function mg(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function bg(e){const[t]=Sd.Validator.isValidIPv4String(e);return t}function Ag(e){const[t]=Sd.Validator.isValidIPv6String(e);return!!t||Ig(e)}function Ig(e){if(e.startsWith("::ffff:"))try{return Sd.IPv6.fromString(e),!0}catch{if(bg(e.slice(7)))return!0}return!1}function vg(e){if(!bg(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function wg(e){const t=e.slice(7);if(bg(t))return t;const r=t.match(/^([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/);if(null==r)throw new TypeError("Invalid IPv4 mapped IPv6 address");return(r[1].padStart(4,"0")+r[2].padStart(4,"0")).match(/.{1,2}/g).map(e=>parseInt(e,16)).join(".")}function Sg(e){const t=new Sd.IPv4("0.0.0.0"),r=new Sd.IPv6("::");if(Ig(e)){const r=wg(e);return new Sd.IPv4(r).isEquals(t)?vg("127.0.0.1"):e}return bg(e)&&new Sd.IPv4(e).isEquals(t)?"127.0.0.1":Ag(e)&&new Sd.IPv6(e).isEquals(r)?"::1":e}async function Eg(e){return(await wd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Cg(e,t){if(bg(e))return[e,"udp4"];if(Ag(e))return[e,"udp6"];try{return Cg(e=await t(e),t)}catch{throw new kd}}function kg(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new xd;return e}function xg(e,t=0){let r;return r=bg(e)?`${e}:${t}`:Ag(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Bg(e,t,r,s,i){if("0.0.0.0"===(n=r)||"::"===n||"::0"===n||"::ffff:0.0.0.0"===n||"::ffff:0:0"===n)throw new i(`Invalid wildcard target host ${r}`);var n;const o=Ig(e),a=Ig(r);if("ipv4&ipv6"===t&&"udp4"===s)return vg(r);if("ipv4"===t){if(o){if("udp4"===s)return vg(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return wg(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||a)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function _g(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(fg.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(fg.decode(r).trim()+"\n");return t}function Rg(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function Og(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function Ug(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function Tg(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Ng(e,t=1e5){En.setMaxListeners(t,e)}class Dg extends ru{}class Mg extends Dg{}class Pg extends Mg{}class Lg extends Mg{}class Hg extends Mg{}class Kg extends Dg{}class Vg extends Kg{}class Qg extends Mg{}class Fg extends Kg{}class Gg extends Dg{}class $g extends Gg{}class jg extends Gg{}class qg extends Gg{}class zg extends Dg{}class Wg extends zg{}class Jg extends zg{}class Yg extends zg{}class Xg extends zg{}class Zg extends zg{}class ef extends Dg{}class tf extends ef{}class rf extends ef{}class sf extends ef{}class nf extends ef{}class of extends ef{}var af=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let cf=class{connectionMap=new Id;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(Og(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[Qu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=vd.Header.fromSlice(e,vd.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new bd(r.dcid),i={host:t.address,port:t.port},n=this.connectionMap.get(s);if(null!=n)await n.recv(e,i);else{if(null==this.server)return;try{await this.server.acceptConnection(i,r,s,e)}catch(e){if(_u(e,e=>e instanceof _d)){const t=new Nd("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new Lg({detail:t})),void this.dispatchEvent(new Hg)}if(e instanceof Gd)return;throw e}}};constructor({resolveHostname:e=Eg,logger:t}){this.logger=t??new eu(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=mg();this._closedP=r,this.resolveClosedP=s}get host(){return this._host}get port(){return this._port}get type(){return this._type}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r=!1,ipv6Only:s=!1}={}){Ng(this[lu]);let i=xg(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await Cg(e,this.resolveHostname),a=kg(t);this.socket=Dh.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=yg(this.socket.bind).bind(this.socket),this.socketClose=yg(this.socket.close).bind(this.socket),this.socketSend=yg(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=mg();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new Ud(e!==n?`Could not bind to resolved ${e} -> ${n}`:`Could not bind to ${e}`,{cause:t})}this.socket.removeListener("error",l);const u=this.socket.address();this._host=u.address,this._port=u.port,"::"!==n||s?"udp4"===o||Ig(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(Lg.name,this.handleEventQUICSocketError),this.addEventListener(Hg.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=xg(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=xg(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Od(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new Hg),await this._closedP;const{p:r,resolveP:s}=mg();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(Lg.name,this.handleEventQUICSocketError),this.removeEventListener(Hg.name,this.handleEventQUICSocketClose),this.socket.off("message",this.handleSocketMessage),this.logger.info(`Stopped ${this.constructor.name} on ${t}`)}async send(...e){let t;if(3===e.length&&"string"==typeof e[2])t=2;else{if(5!==e.length||"string"!=typeof e[4])throw new TypeError("QUICSocket.send requires `port` and `address` parameters");t=4}const r=e[t];let[s,i]=await Cg(r,this.resolveHostname);return s=Sg(s),s=Bg(this._host,this._type,s,i,Td),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};af([yd(new Rd)],cf.prototype,"host",null),af([yd(new Rd)],cf.prototype,"port",null),af([yd(new Rd)],cf.prototype,"type",null),af([yd(new Rd)],cf.prototype,"send",null),af([yd(new Rd)],cf.prototype,"send_",null),cf=af([pd({eventStart:class extends Mg{},eventStarted:class extends Mg{},eventStop:class extends Mg{},eventStopped:Pg})],cf);const lf=cf,hf=new WeakMap;const uf=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(hf.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);hf.set(i,r)};class df extends Bu{static description="Contexts error"}class gf extends df{static description="Aborted due to timer expiration"}const ff=function(e=!1,t=1/0,r=gf){return(s,i,n)=>{const o=s.name??s.constructor.name,a=n.value;if("function"!=typeof a)throw new TypeError(`\`${o}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=hf.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,o);return n.value=function(...s){let n=s[c];return n=void 0===n?{}:{...n},s[c]=n,function(e,t,r){if("object"!=typeof e||null===e)throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter is not a context object`);if(void 0!==e.signal&&!(e.signal instanceof AbortSignal))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`signal\` property is not an instance of \`AbortSignal\``);if(void 0!==e.timer&&!("number"==typeof e.timer||e.timer instanceof Tu))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,o),function(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new Tu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Tu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new Tu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new Su((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}((e,...t)=>a.apply(this,t),"boolean"==typeof e?e:e(this),"number"==typeof t?t:t(this),r,n,s)},Object.defineProperty(n.value,"name",{value:"symbol"==typeof i?`[${i.description}]`:i}),n}},pf=["rsa_pkcs1_sha256","rsa_pkcs1_sha384","rsa_pkcs1_sha512","rsa_pss_rsae_sha256","rsa_pss_rsae_sha384","rsa_pss_rsae_sha512","ecdsa_secp256r1_sha256","ecdsa_secp384r1_sha384","ecdsa_secp521r1_sha512","ed25519"].join(":"),yf=1/0,mf={sigalgs:pf,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:vd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:vd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:vd.MAX_CONNECTION_WINDOW,maxStreamWindow:vd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},bf={sigalgs:pf,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:vd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:vd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:vd.MAX_CONNECTION_WINDOW,maxStreamWindow:vd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Af=t(import.meta.url)("stream/web");var If=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};const vf=Symbol("abort readableP reason");let wf=class{static createQUICStream({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i=()=>0,codeToReason:n=(e,t)=>new Error(`${e.toString()} ${t.toString()}`),logger:o=new eu(`${this.name} ${t}`)}){o.info(`Create ${this.name}`);const a=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o});return"uni"===a.type&&("local"===e?(a.readableController.close(),a._readClosed=!0):"peer"===e&&(a.writable.close().catch(()=>{}),a._writeClosed=!0)),a.addEventListener(rf.name,a.handleEventQUICStreamError),a.addEventListener(sf.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(nf.name,a.handleEventQUICStreamCloseWrite,{once:!0}),o.info(`Created ${this.name}`),a}type;initiated;streamId;readable;writable;closedP;logger;connection;reasonToCode;codeToReason;readableController;writableController;_readClosed=!1;_writeClosed=!1;readableChunk;resolveReadableP;rejectReadableP;resolveWritableP;rejectWritableP;resolveClosedP;handleEventQUICStreamError=e=>{const t=e.detail;if(t instanceof ug)throw this.logger.debug(Og(t)),t;t instanceof ag||t instanceof lg?this.dispatchEvent(new sf({detail:t})):(t instanceof cg||t instanceof hg)&&this.dispatchEvent(new nf({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Gu]||"destroying"===this[ju]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Gu]||"destroying"===this[ju]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=o,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:a,resolveP:c}=mg();if(this.closedP=a,this.resolveClosedP=c,"uni"===this.type&&"local"===e?this.readableChunk=void 0:this.readableChunk=Buffer.allocUnsafe(s.readableChunkSize),"uni"===this.type&&"local"===e?this.readable=new Af.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new Af.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new Af.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new Af.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new Af.WritableStream({start:this.writableStart.bind(this),write:this.writableWrite.bind(this),close:this.writableClose.bind(this),abort:this.writableAbort.bind(this)},{highWaterMark:1});try{r.conn.streamSend(t,new Uint8Array(0),!1)}catch(e){if(!1===Ug(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new dg(`Stream limit of ${t} has been reached`,{cause:e})}throw new ug(`Failed to prime local stream state with a 0-length message: ${e.message}`,{cause:e})}}}}get writeClosed(){return this._writeClosed}get readClosed(){return this._readClosed}get meta(){return this.connection.meta()}get closed(){return this._readClosed&&this._writeClosed}async destroy({force:e=!0,reason:t}={}){this.logger.info(`Destroy ${this.constructor.name}`),!e||this._readClosed&&this._writeClosed||this.cancel(t),await this.closedP,this.removeEventListener(rf.name,this.handleEventQUICStreamError),this.removeEventListener(sf.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(nf.name,this.handleEventQUICStreamCloseWrite),this.logger.info(`Destroyed ${this.constructor.name}`)}cancel(e){this.readableCancel(e),this.writableAbort(e)}read(){if(this.connection.conn.streamFinished(this.streamId)){let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=Tg(e))){const e=this.codeToReason("read",t),r=new lg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new rf({detail:r}))}{const t=new ug("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new rf({detail:t})),t}}if(null===e){const e=new ug("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new rf({detail:e})),e}const[t]=e;return t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),this.readableController.close(),this.dispatchEvent(new sf),void this.rejectReadableP?.(vf)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=Ug(e))){this.connection.conn.streamShutdown(this.streamId,vd.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new hg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new rf({detail:r}))}{const t=new ug("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new rf({detail:t})),t}}this.resolveWritableP?.()}readableStart(e){this.readableController=e}writableStart(e){this.writableController=e}async readablePull(){if(!this.connection.conn.streamReadable(this.streamId)){const{p:e,resolveP:t,rejectP:r}=mg();e.catch(()=>{}),this.resolveReadableP=t,this.rejectReadableP=r;try{await e}catch(e){return}}let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=Tg(e))){const e=this.codeToReason("read",t),r=new lg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new rf({detail:r}))}{const t=new ug("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new rf({detail:t})),t}}if(null===e){const e=new ug("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new rf({detail:e})),e}const[t,r]=e;t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),r&&(this.readableController.close(),this.dispatchEvent(new sf)),this.dispatchEvent(new of)}async writableWrite(e){if(0===e.byteLength)return;let t;for(;;){try{const r=this.connection.conn.streamSend(this.streamId,e,!1);t=null===r?0:r}catch(e){let t;if(!1!==(t=Ug(e))){const e=this.codeToReason("write",t),r=new hg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new rf({detail:r}))}{const t=new ug("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new rf({detail:t})),t}}if(this.dispatchEvent(new of),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=mg();r.catch(()=>{}),this.resolveWritableP=s,this.rejectWritableP=i,await r;continue}return}}writableClose(){try{this.connection.conn.streamSend(this.streamId,new Uint8Array(0),!0)}catch(e){let t;if(!1!==(t=Ug(e))){const e=this.codeToReason("write",t),r=new hg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new rf({detail:r}))}{const t=new ug("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new rf({detail:t})),t}}this.dispatchEvent(new nf),this.dispatchEvent(new of)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,vd.Shutdown.Read,t)}catch(r){const e=new ug("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new rf({detail:e})),e}const r=new ag("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new rf({detail:r})),this.dispatchEvent(new of)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,vd.Shutdown.Write,t)}catch(r){const e=new ug("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new rf({detail:e})),e}const r=new cg("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new rf({detail:r})),this.dispatchEvent(new of)}};If([fd(new og)],wf.prototype,"meta",null),If([fd(new og,!1,["destroying"])],wf.prototype,"read",null),If([fd(new og,!1,["destroying"])],wf.prototype,"write",null),wf=If([gd({eventDestroy:class extends ef{},eventDestroyed:tf})],wf);const Sf=wf;var Ef,Cf,kf,xf,Bf,_f;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(Ef||(Ef={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Cf||(Cf={})),function(e){e[e.Initial=0]="Initial",e[e.Retry=1]="Retry",e[e.Handshake=2]="Handshake",e[e.ZeroRTT=3]="ZeroRTT",e[e.VersionNegotiation=4]="VersionNegotiation",e[e.Short=5]="Short"}(kf||(kf={})),function(e){e[e.NoError=0]="NoError",e[e.InternalError=1]="InternalError",e[e.ConnectionRefused=2]="ConnectionRefused",e[e.FlowControlError=3]="FlowControlError",e[e.StreamLimitError=4]="StreamLimitError",e[e.StreamStateError=5]="StreamStateError",e[e.FinalSizeError=6]="FinalSizeError",e[e.FrameEncodingError=7]="FrameEncodingError",e[e.TransportParameterError=8]="TransportParameterError",e[e.ConnectionIdLimitError=9]="ConnectionIdLimitError",e[e.ProtocolViolation=10]="ProtocolViolation",e[e.InvalidToken=11]="InvalidToken",e[e.ApplicationError=12]="ApplicationError",e[e.CryptoBufferExceeded=13]="CryptoBufferExceeded",e[e.KeyUpdateError=14]="KeyUpdateError",e[e.AEADLimitReached=15]="AEADLimitReached",e[e.NoViablePath=16]="NoViablePath"}(xf||(xf={})),(_f=Bf||(Bf={}))[_f.CloseNotify=256]="CloseNotify",_f[_f.UnexpectedMessage=266]="UnexpectedMessage",_f[_f.BadRecordMac=276]="BadRecordMac",_f[_f.RecordOverflow=278]="RecordOverflow",_f[_f.HandshakeFailure=296]="HandshakeFailure",_f[_f.BadCertificate=298]="BadCertificate",_f[_f.UnsupportedCertificate=299]="UnsupportedCertificate",_f[_f.CertificateRevoked=300]="CertificateRevoked",_f[_f.CertificateExpired=301]="CertificateExpired",_f[_f.CertificateUnknown=302]="CertificateUnknown",_f[_f.IllegalParameter=303]="IllegalParameter",_f[_f.UnknownCA=304]="UnknownCA",_f[_f.AccessDenied=305]="AccessDenied",_f[_f.DecodeError=306]="DecodeError",_f[_f.DecryptError=307]="DecryptError",_f[_f.ProtocolVersion=326]="ProtocolVersion",_f[_f.InsufficientSecurity=327]="InsufficientSecurity",_f[_f.InternalError=336]="InternalError",_f[_f.InappropriateFallback=342]="InappropriateFallback",_f[_f.UserCanceled=346]="UserCanceled",_f[_f.MissingExtension=365]="MissingExtension",_f[_f.UnsupportedExtension=366]="UnsupportedExtension",_f[_f.UnrecognizedName=368]="UnrecognizedName",_f[_f.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",_f[_f.UnknownPSKIdentity=371]="UnknownPSKIdentity",_f[_f.CertificateRequired=372]="CertificateRequired",_f[_f.NoApplicationProtocol=376]="NoApplicationProtocol";var Rf=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Of=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Hu;streamIdClientBidi=0;streamIdServerBidi=1;streamIdClientUni=2;streamIdServerUni=3;streamIdUsedClientBidi=-4;streamIdUsedServerBidi=-3;streamIdUsedClientUni=-2;streamIdUsedServerUni=-1;streamIdUsedSet=new Set;connTimeoutTimer;keepAliveIntervalTimer;_remoteHost;_remotePort;certDERs=[];caDERs=[];secureEstablished=!1;secureEstablishedP;resolveSecureEstablishedP;rejectSecureEstablishedP;resolveClosedP;errorLast=null;handleEventQUICConnectionError=e=>{const t=e.detail;if(this.errorLast=t,this.logger.info(Og(t)),t instanceof ig)throw t;this.dispatchEvent(new Yg({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof Zd&&await this.send(),this[Qu]&&"stopping"!==this[ju]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof ru&&!(e.detail instanceof of)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[Qu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(of.name,this.handleEventQUICStreamSend),t.removeEventListener(ou.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:o,reasonToCode:a=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new eu(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new Xd("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new Bd("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new Bd("The key option must be set when cert is set");if(null!=e.key&&null!=e.cert&&Array.isArray(e.key)&&Array.isArray(e.cert)&&e.key.length!==e.cert.length)throw new Bd("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=_g(e.ca);t=gg.encode(r.join(""))}null!=e.key&&(r=_g(e.key).map(e=>gg.encode(e))),null!=e.cert&&(s=_g(e.cert).map(e=>gg.encode(e)));try{i=vd.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new Bd(`Failed to build Quiche config with custom SSL context: ${e.message}`,{cause:e})}return null!=e.logKeys&&i.logKeys(),e.enableEarlyData&&i.enableEarlyData(),i.grease(e.grease),i.setMaxIdleTimeout(e.maxIdleTimeout),i.setMaxRecvUdpPayloadSize(e.maxRecvUdpPayloadSize),i.setMaxSendUdpPayloadSize(e.maxSendUdpPayloadSize),i.setInitialMaxData(e.initialMaxData),i.setInitialMaxStreamDataBidiLocal(e.initialMaxStreamDataBidiLocal),i.setInitialMaxStreamDataBidiRemote(e.initialMaxStreamDataBidiRemote),i.setInitialMaxStreamDataUni(e.initialMaxStreamDataUni),i.setInitialMaxStreamsBidi(e.initialMaxStreamsBidi),i.setInitialMaxStreamsUni(e.initialMaxStreamsUni),i.enableDgram(...e.enableDgram),i.setDisableActiveMigration(e.disableActiveMigration),i.setApplicationProtos(e.applicationProtos),i}(n);let u;if("client"===e?(this.logger.info(`Connect ${this.constructor.name}`),u=vd.Connection.connect(s,t,{host:o.host,port:o.port},{host:i.host,port:i.port},h)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=vd.Connection.accept(t,r,{host:o.host,port:o.port},{host:i.host,port:i.port},h)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=o,this.config=n,null!=this.config.cert){const e=_g(this.config.cert);this.certDERs=e.map(Rg)}if(null!=this.config.ca){const e=_g(this.config.ca);this.caDERs=e.map(Rg)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:g,rejectP:f}=mg();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,g()},this.rejectSecureEstablishedP=f;const{p,resolveP:y}=mg();this.closedP=p,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new bd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new bd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new bd(Buffer.concat([e,t])):new bd(Buffer.concat([t,e]))}get remoteHost(){return this._remoteHost}get remotePort(){return this._remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this.conn.isClosed()}async start({data:e,remoteInfo:t}={},r){if(this.logger.info(`Start ${this.constructor.name}`),this.conn.isClosed())throw new Jd;r.signal.throwIfAborted();const{p:s,rejectP:i}=mg();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Jg.name,this.handleEventQUICConnectionError),this.addEventListener(Yg.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new Yd("Starting a server connection requires initial data and remote information");await this.recv(e,t)}try{await Promise.race([this.secureEstablishedP,s])}catch(e){if(r.signal.aborted){for(const t of this.conn.readable())this.conn.streamShutdown(t,vd.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,vd.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,xf.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new Zd("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Jg({detail:r}))}throw await this.closedP,e}finally{r.signal.removeEventListener("abort",n)}null!=this.config.keepAliveIntervalTime&&this.startKeepAliveIntervalTimer(this.config.keepAliveIntervalTime),this.logger.info(`Started ${this.constructor.name}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){this.logger.info(`Stop ${this.constructor.name}`),this.stopKeepAliveIntervalTimer(),await async function(){return await new Promise(e=>queueMicrotask(e))}();const i=[];for(const e of this.streamMap.values())i.push(e.destroy({reason:this.errorLast,force:s||this.conn.isDraining()||this.conn.isClosed()}));if(await Promise.all(i),!this.conn.isDraining()&&!this.conn.isClosed()){this.conn.close(e,t,r);const s=this.conn.localError(),i=`Locally closed with ${s.isApp?"application":"transport"} code ${s.errorCode}`,n=new Zd(i,{data:s});this.dispatchEvent(new Jg({detail:n}))}await this.closedP,this.removeEventListener(Jg.name,this.handleEventQUICConnectionError),this.removeEventListener(Yg.name,this.handleEventQUICConnectionClose),this.logger.info(`Stopped ${this.constructor.name}`)}getConnectionError(){return this.conn.localError()??this.conn.peerError()??void 0}getLocalCACertsChain(){return this.caDERs}getLocalCertsChain(){return this.certDERs}getRemoteCertsChain(){return this.conn.peerCertChain()??[]}meta(){return{localHost:this.localHost,localPort:this.localPort,remoteHost:this.remoteHost,remotePort:this.remotePort,localCertsChain:this.certDERs,localCACertsChain:this.caDERs,remoteCertsChain:this.getRemoteCertsChain()}}async recv(e,t){await this.recvLock.withF(async()=>{const r={to:{host:this.localHost,port:this.localPort},from:{host:t.host,port:t.port}};try{this.conn.recv(e,r)}catch(e){const t=this.conn.localError();if(null==t){const t=new ig("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Jg({detail:t})),t}{let r;return r="TlsFail"===e.message?new eg("Failed connection due to native TLS verification",{cause:e,data:t}):new Zd("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Jg({detail:r}))}}this._remoteHost=t.host,this._remotePort=t.port,!this.secureEstablished&&this.conn.isEstablished()&&null==this.config.verifyCallback&&this.resolveSecureEstablishedP(),this.secureEstablished&&this.processStreams(),await this.send()})}async send(){let e,t;for(;;){const r=Buffer.allocUnsafe(this.config.maxSendUdpPayloadSize);try{const s=this.conn.send(r);if(null===s)break;[e,t]=s}catch(e){const t=new ig("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Jg({detail:t})),t}this.dispatchEvent(new Zg({detail:{id:this.sendId,msg:r.subarray(0,e),port:t.to.port,address:t.to.host}}))}if(this.setConnTimeoutTimer(),!this.secureEstablished&&!this.conn.isDraining()&&!this.conn.isClosed()&&this.conn.isEstablished()&&this.config.verifyPeer&&null!=this.config.verifyCallback){const e=this.conn.peerCertChain(),t=await this.config.verifyCallback(e,this.caDERs);if(null!=t){this.conn.close(!1,t,Buffer.from(""));const e=this.conn.localError(),r=new eg("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Jg({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[ju]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=vd.CRYPTO_ERROR_START&&e.errorCode<=vd.CRYPTO_ERROR_STOP?this.dispatchEvent(new Jg({detail:new rg(t,{data:e})})):this.dispatchEvent(new Jg({detail:new tg(t,{data:e})})))}}}isStreamUsed(e){let t;switch(3&e){case 0:if(t=this.streamIdUsedClientBidi+4,e<=this.streamIdUsedClientBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 1:if(t=this.streamIdUsedServerBidi+4,e<=this.streamIdUsedServerBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 2:if(t=this.streamIdUsedClientUni+4,e<=this.streamIdUsedClientUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 3:if(t=this.streamIdUsedServerUni+4,e<=this.streamIdUsedServerUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;default:pg("got an unexpected ID type")}}processStreams(){for(const e of this.conn.readable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Qu]||"stopping"===this[ju]){this.conn.streamShutdown(e,Cf.Write,this.reasonToCode("write",zd)),this.conn.streamShutdown(e,Cf.Read,this.reasonToCode("read",zd));continue}this.isStreamUsed(e)&&pg("We should never repeat streamIds when creating streams"),t=Sf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Sf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(of.name,this.handleEventQUICStreamSend),t.addEventListener(tf.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ou.name,this.handleEventQUICStream),this.dispatchEvent(new Xg({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Qu]||"stopping"===this[ju]){this.conn.streamShutdown(e,Cf.Write,this.reasonToCode("write",zd)),this.conn.streamShutdown(e,Cf.Read,this.reasonToCode("read",zd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==Ug(e))continue;if("FinalSize"===e.message)continue;throw e}pg("We never expect a duplicate stream to be readable")}t=Sf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Sf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(of.name,this.handleEventQUICStreamSend),t.addEventListener(tf.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ou.name,this.handleEventQUICStream),this.dispatchEvent(new Xg({detail:t}))}t.write()}}setConnTimeoutTimer(){const e=async t=>{if(t.aborted)return;if(this.conn.onTimeout(),this.conn.isClosed())return this.resolveClosedP(),void(this.conn.isTimedOut()&&this.dispatchEvent(new Jg({detail:new sg})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new Tu({delay:r+1,handler:e,lazy:!0}))},t=this.conn.timeout();if(null==t)return this.connTimeoutTimer?.cancel(),delete this.connTimeoutTimer,void(this.conn.isClosed()&&(this.resolveClosedP(),this.conn.isTimedOut()&&this.dispatchEvent(new Jg({detail:new sg}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new Tu({delay:t+1,handler:e,lazy:!0}):null==this.connTimeoutTimer.status&&this.connTimeoutTimer.reset(t+1)}newStream(e="bidi"){let t;"client"===this.type&&"bidi"===e?t=this.streamIdClientBidi:"server"===this.type&&"bidi"===e?t=this.streamIdServerBidi:"client"===this.type&&"uni"===e?t=this.streamIdClientUni:"server"===this.type&&"uni"===e&&(t=this.streamIdServerUni),this.isStreamUsed(t)&&pg("We should never repeat streamIds when creating streams");const r=Sf.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Sf.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(of.name,this.handleEventQUICStreamSend),r.addEventListener(tf.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(ou.name,this.handleEventQUICStream),"client"===this.type&&"bidi"===e?this.streamIdClientBidi=this.streamIdClientBidi+4:"server"===this.type&&"bidi"===e?this.streamIdServerBidi=this.streamIdServerBidi+4:"client"===this.type&&"uni"===e?this.streamIdClientUni=this.streamIdClientUni+4:"server"===this.type&&"uni"===e&&(this.streamIdServerUni=this.streamIdServerUni+4),r}destroyStreams(e){for(const t of this.streamMap.values())t.cancel(e)}startKeepAliveIntervalTimer(e){const t=async r=>{r.aborted||(this.conn.sendAckEliciting(),await this.send(),r.aborted||(this.keepAliveIntervalTimer=new Tu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new Tu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var Uf,Tf;Rf([yd(new Wd)],Of.prototype,"connectionIdPeer",null),Rf([yd(new Wd)],Of.prototype,"connectionIdShared",null),Rf([ff(!0,yf,class extends qd{static description="QUIC Connection start timeout"}),(Uf=1,Tf=uf,function(e,t){Tf(e,t,Uf)})],Of.prototype,"start",null),Rf([yd(new Wd,!1,["starting","stopping"])],Of.prototype,"recv",null),Rf([yd(new Wd,!1,["starting","stopping"])],Of.prototype,"send",null),Rf([yd(new Wd)],Of.prototype,"newStream",null),Of=Rf([pd({eventStart:class extends zg{},eventStarted:class extends zg{},eventStop:class extends zg{},eventStopped:Wg})],Of);const Nf=Of;var Df=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Mf=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(Og(t)),t instanceof $d)throw t;this.dispatchEvent(new qg({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof Fd||this.isSocketShared)){this.socket.removeEventListener(Pg.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new $d("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new jg({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Qu]&&"stopping"!==this[ju]&&(void 0!==t?await this.stop({isApp:!1,errorCode:xf.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof ru&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Fd;this.removeEventListener(ou.name,this.handleEventQUICSocket),this.dispatchEvent(new jg({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof ru&&!(e.detail instanceof Zg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[Qu]&&"stopping"!==this.socket[ju])try{await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Qg(`${Qg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new jg({detail:new $d("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Zg.name,this.handleEventQUICConnectionSend),t.removeEventListener(ou.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Eg,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new eu(this.constructor.name),this.crypto=e,null==r?(this.socket=new lf({resolveHostname:s,logger:this.logger.getChild(lf.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...bf,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=mg();this._closedP=c,this.resolveClosedP=l}get host(){return this.socket.host}get port(){return this.socket.port}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r,ipv6Only:s}={}){let i;if(this.stopAbortController=new AbortController,Ng(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[Qu])throw new Fd;i=xg(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=xg(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=xg(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(jg.name,this.handleEventQUICServerError),this.addEventListener(qg.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Pg.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(ou.name,this.handleEventQUICSocket),this._closed=!1,this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.socket[Qu]&&(i=xg(this.socket.host,this.socket.port)),this.logger.info(`Stop ${this.constructor.name}${null!=i?` on ${i}`:""}`),this.socket.unsetServer();const n=[];s&&this.stopAbortController?.abort(new jd),this.stopAbortController=void 0;for(const i of this.socket.connectionMap.serverConnections.values())n.push(i.stop({isApp:e,errorCode:t,reason:r,force:s}));await Promise.all(n),this._closed||this.dispatchEvent(new qg),await this._closedP;const{p:o,resolveP:a}=mg();this._closedP=o,this.resolveClosedP=a,this.removeEventListener(jg.name,this.handleEventQUICServerError),this.removeEventListener(qg.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Pg.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ou.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==vd.Type.Initial&&t.ty!==vd.Type.ZeroRTT)return;const i=new bd(await this.crypto.ops.sign(this.crypto.key,r),0,vd.MAX_CONN_ID_LEN),n=xg(e.host,e.port);if(!vd.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(vd.MAX_DATAGRAM_SIZE),s=vd.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new Gd(`Failed to send version datagram ${n}`,{cause:e})}return}const o=t.token;if(0===o.byteLength){const s=await this.mintToken(r,e.host),o=Buffer.allocUnsafe(vd.MAX_DATAGRAM_SIZE),a=vd.retry(t.scid,t.dcid,i,s,t.version,o);try{await this.socket.send_(o,0,a,e.port,e.host)}catch(e){throw new Gd(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const a=await this.validateToken(Buffer.from(o),e.host);if(null==a)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new bd(t.dcid),l=new Nf({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${Nf.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(Zg.name,this.handleEventQUICConnectionSend),l.addEventListener(Wg.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(ou.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(Zg.name,this.handleEventQUICConnectionSend),l.removeEventListener(Wg.name,this.handleEventQUICConnectionStopped),l.removeEventListener(ou.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new Gd("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new $g({detail:l})),l}updateCrypto(e){this.crypto={...this.crypto,...e}}updateConfig(e){this.config={...this.config,...e}}async mintToken(e,t){return async function(e,t,r){const s={dcid:e.toString(),host:t},i=JSON.stringify(s),n=Buffer.from(i),o=Buffer.from(await r.ops.sign(r.key,n)),a={msg:n.toString("base64url"),sig:o.toString("base64url")},c=JSON.stringify(a);return Buffer.from(c)}(e,t,this.crypto)}async validateToken(e,t){return async function(e,t,r){let s;try{s=JSON.parse(e.toString())}catch{return}if("object"!=typeof s||null==s)return;if("string"!=typeof s.msg||"string"!=typeof s.sig)return;const i=Buffer.from(s.msg,"base64url"),n=Buffer.from(s.sig,"base64url");if(!await r.ops.verify(r.key,i,n))return;let o;try{o=JSON.parse(i.toString())}catch{return}return"object"==typeof o&&null!=o&&"string"==typeof o.dcid&&"string"==typeof o.host&&o.host===t?bd.fromString(o.dcid):void 0}(e,t,this.crypto)}};Df([yd(new Qd)],Mf.prototype,"host",null),Df([yd(new Qd)],Mf.prototype,"port",null),Df([yd(new Qd)],Mf.prototype,"acceptConnection",null),Mf=Df([pd({eventStart:class extends Gg{},eventStarted:class extends Gg{},eventStop:class extends Gg{},eventStopped:class extends Gg{}})],Mf);var Pf=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Lf=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=Eg,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:g=new eu(`${this.name}`)},f){let p=xg(e,t);g.info(`Create ${this.name} to ${p}`);const y={...mf,...a},m=new ArrayBuffer(vd.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new bd(m);let[A,I]=await Cg(e,c);const v=kg(t);let w,S;if(A=Sg(A),null==n){const[e]=await Cg(s,c),t=kg(i);n=new lf({resolveHostname:c,logger:g.getChild(lf.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[Qu])throw new Fd;try{A=Bg(n.host,n.type,A,I,Hd)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new Nf({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:g.getChild(`${Nf.name} ${b.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:g});w||n.addEventListener(ou.name,E.handleEventQUICSocket),n.addEventListener(Pg.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(ou.name,E.handleEventQUICConnection),S.addEventListener(Jg.name,E.handleEventQUICConnectionError),S.addEventListener(Zg.name,E.handleEventQUICConnectionSend),S.addEventListener(Wg.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(Vg.name,E.handleEventQUICClientError),E.addEventListener(Fg.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(f.signal.reason)};f.signal.aborted?C.abort(f.signal.reason):f.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Ld(void 0,{cause:e.detail}))}};E.addEventListener(`${Qg.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:f.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Pg.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(ou.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(ou.name,E.handleEventQUICConnection),S.removeEventListener(Jg.name,E.handleEventQUICConnectionError),S.removeEventListener(Zg.name,E.handleEventQUICConnectionSend),S.removeEventListener(Wg.name,E.handleEventQUICConnectionStopped),E.removeEventListener(Vg.name,E.handleEventQUICClientError),E.removeEventListener(Fg.name,E.handleEventQUICClientClose),e}finally{f.signal.removeEventListener("abort",k),E.removeEventListener(`${Qg.name}-${S.sendId}`,x)}return p=xg(A,t),g.info(`Created ${this.name} to ${p}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(Og(t)),t instanceof Kd||t instanceof ig)throw t;this.dispatchEvent(new Fg({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Jg.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:xf.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Pd||this.isSocketShared)){this.socket.removeEventListener(Pg.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Kd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Vg({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Gu]||"destroying"===this[ju]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof ru&&!(e.detail instanceof Zg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Pd;this.removeEventListener(ou.name,this.handleEventQUICSocket),this.dispatchEvent(new Vg({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof ru&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new Vg({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[Qu]||"stopping"===this.socket[ju])return;await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Qg(`${Qg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Vg({detail:new Kd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Jg.name,this.handleEventQUICConnectionError),t.removeEventListener(Zg.name,this.handleEventQUICConnectionSend),t.removeEventListener(ou.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({socket:e,isSocketShared:t,connection:r,logger:s}){this.logger=s,this.socket=e,this.isSocketShared=t,this.connection=r;const{p:i,resolveP:n}=mg();this.closedP=i,this.resolveClosedP=n}get host(){return this.connection.remoteHost}get port(){return this.connection.remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this._closed}async destroy({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.connection[Qu]&&(i=xg(this.connection.remoteHost,this.connection.remotePort)),this.logger.info(`Destroy ${this.constructor.name}${null!=i?` to ${i}`:""}`),this._closed||await this.connection.stop({isApp:e,errorCode:t,reason:r,force:s}),await this.closedP,this.removeEventListener(Vg.name,this.handleEventQUICClientError),this.removeEventListener(Fg.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Pg.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ou.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Pf([fd(new Md)],Lf.prototype,"host",null),Pf([fd(new Md)],Lf.prototype,"port",null),Pf([fd(new Md)],Lf.prototype,"localHost",null),Pf([fd(new Md)],Lf.prototype,"localPort",null),Pf([ff(!0,yf,class extends Dd{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,uf)],Lf,"createQUICClient",null),Lf=Pf([gd({eventDestroy:class extends Kg{},eventDestroyed:class extends Kg{}})],Lf),t(import.meta.url)("node:crypto");class Hf{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const r=Hf.toUint8Array(e),s=Hf.toUint8Array(t);if(r.length!==s.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const s=new Uint8Array(r);let i=0;for(const e of t){const t=this.toUint8Array(e);s.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const Kf="string",Vf=/^[0-9a-f\s]+$/i,Qf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ff=/^[a-zA-Z0-9-_]+$/;class Gf{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=Hf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class $f{static toString(e,t=!1){const r=Hf.toArrayBuffer(e),s=new DataView(r);let i="";for(let e=0;e<r.byteLength;e+=2){const r=s.getUint16(e,t);i+=String.fromCharCode(r)}return i}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),s=new DataView(r);for(let r=0;r<e.length;r++)s.setUint16(2*r,e.charCodeAt(r),t);return r}}class jf{static isHex(e){return typeof e===Kf&&Vf.test(e)}static isBase64(e){return typeof e===Kf&&Qf.test(e)}static isBase64Url(e){return typeof e===Kf&&Ff.test(e)}static ToString(e,t="utf8"){const r=Hf.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return $f.toString(r,!0);case"utf16":case"utf16be":return $f.toString(r);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return $f.fromString(e,!0);case"utf16":case"utf16be":return $f.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=Hf.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!jf.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!jf.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=jf.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Gf.fromString(e);case"utf16":case"utf16be":return $f.fromString(e);case"utf16le":case"usc2":return $f.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=jf.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Gf.toString(e);case"utf16":case"utf16be":return $f.toString(e);case"utf16le":case"usc2":return $f.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return r.buffer}static ToBinary(e){const t=Hf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=Hf.toUint8Array(e);let r="";const s=t.length;for(let e=0;e<s;e++){const s=t[e];s<16&&(r+="0"),r+=s.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!jf.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const s=t.slice(e,e+2);r[e/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(e,t=!1){return $f.toString(e,t)}static FromUtf16String(e,t=!1){return $f.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function qf(...e){const t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(t);let s=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(const t of e)r[s++]=t}),r.buffer}function zf(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}function Wf(e,t){let r=0;if(1===e.length)return e[0];for(let s=e.length-1;s>=0;s--)r+=e[e.length-1-s]*Math.pow(2,t*s);return r}function Jf(e,t,r=-1){const s=r;let i=e,n=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e<o){let e;if(s<0)e=new ArrayBuffer(r),n=r;else{if(s<r)return new ArrayBuffer(0);e=new ArrayBuffer(s),n=s}const o=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);o[n-e-1]=Math.floor(i/r),i-=o[n-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function Yf(...e){let t=0,r=0;for(const r of e)t+=r.length;const s=new ArrayBuffer(t),i=new Uint8Array(s);for(const t of e)i.set(t,r),r+=t.length;return i}function Xf(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const s=Wf(r,8),i=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)n[t]=e[t];return n[0]&=127,Wf(n,8)-s}function Zf(e,t){const r=e.toString(10);if(t<r.length)return"";const s=t-r.length,i=new Array(s);for(let e=0;e<s;e++)i[e]="0";return i.join("").concat(r)}function ep(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function tp(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const s=new Uint8Array(t);for(let t=0;t<e.length;t++){const i=e[t];s.set(new Uint8Array(i),r),r+=i.byteLength}return s.buffer}function rp(e,t,r,s){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):s<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-s<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}jf.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class sp{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return tp(this.items)}}const ip=[new Uint8Array([1])],np="0123456789",op="name",ap="valueHexView",cp="isHexOnly",lp="idBlock",hp="tagClass",up="tagNumber",dp="isConstructed",gp="fromBER",fp="toBER",pp="local",yp="",mp=new ArrayBuffer(0),bp=new Uint8Array(0),Ap="EndOfContent",Ip="OCTET STRING",vp="BIT STRING";function wp(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?Hf.toUint8Array(r.valueHex):bp}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!rp(this,s,t,r))return-1;const i=t+r;return this.valueHexView=s.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",mp)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:jf.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Sp{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=yp,warnings:r=[],valueBeforeDecode:s=bp}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Hf.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:jf.ToHex(this.valueBeforeDecodeView)}}}Sp.NAME="baseBlock";class Ep extends Sp{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ep.NAME="valueBlock";class Cp extends(wp(Sp)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?Hf.toUint8Array(e.valueHex):bp,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(s=e.tagNumber)&&void 0!==s?s:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",mp}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=Jf(this.tagNumber,7),s=new Uint8Array(r),i=r.byteLength,n=new Uint8Array(i+1);if(n[0]=31|t,!e){for(let e=0;e<i-1;e++)n[e+1]=128|s[e];n[i]=s[i-1]}return n.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const s=Hf.toUint8Array(e);if(!rp(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;const n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&i[e];){if(t[e-1]=127&i[e],e++,e>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&i[e];const s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(s),this.blockLength<=9?this.tagNumber=Wf(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Cp.NAME="identificationBlock";class kp extends Sp{constructor({lenBlock:e={}}={}){var t,r,s;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(s=e.length)&&void 0!==s?s:0}fromBER(e,t,r){const s=Hf.toUint8Array(e);if(!rp(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;const n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=s.subarray(o,o+n);return 0===a[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=Wf(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const s=Jf(this.length,8);if(s.byteLength>127)return this.error="Too big length",mp;if(t=new ArrayBuffer(s.byteLength+1),e)return t;const i=new Uint8Array(s);r=new Uint8Array(t),r[0]=128|s.byteLength;for(let e=0;e<s.byteLength;e++)r[e+1]=i[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}kp.NAME="lengthBlock";const xp={};class Bp extends Sp{constructor({name:e=yp,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Cp(s),this.lenBlock=new kp(s),this.valueBlock=i?new i(s):new Ep(s)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){const r=t||new sp;t||_p(this);const s=this.idBlock.toBER(e);if(r.write(s),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const s=this.lenBlock.toBER(e);r.write(s),r.write(t)}return t?mp:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():jf.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${jf.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}(this.toBER(),e.toBER())}}function _p(e){var t;if(e instanceof xp.Constructed)for(const t of e.valueBlock.value)_p(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}Bp.NAME="BaseBlock";class Rp extends Bp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=yp,...t}={},r){super(t,r),e&&this.fromString(e)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Rp.NAME="BaseStringBlock";class Op extends(wp(Ep)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var Up,Tp,Np,Dp,Mp,Pp,Lp,Hp,Kp,Vp,Qp,Fp,Gp,$p,jp,qp,zp,Wp,Jp,Yp,Xp,Zp,ey,ty,ry,sy,iy,ny,oy,ay,cy,ly,hy,uy,dy,gy;Op.NAME="PrimitiveValueBlock";class fy extends Bp{constructor(e={}){super(e,Op),this.idBlock.isConstructed=!1}}function py(e,t=0,r=e.length){const s=t;let i=new Bp({},Ep);const n=new Sp;if(!rp(n,e,t,r))return i.error=n.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let o=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===o)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=o,r-=i.idBlock.blockLength,o=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===o)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=o,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let a=Bp;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};a=xp.EndOfContent;break;case 1:a=xp.Boolean;break;case 2:a=xp.Integer;break;case 3:a=xp.BitString;break;case 4:a=xp.OctetString;break;case 5:a=xp.Null;break;case 6:a=xp.ObjectIdentifier;break;case 10:a=xp.Enumerated;break;case 12:a=xp.Utf8String;break;case 13:a=xp.RelativeObjectIdentifier;break;case 14:a=xp.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=xp.Sequence;break;case 17:a=xp.Set;break;case 18:a=xp.NumericString;break;case 19:a=xp.PrintableString;break;case 20:a=xp.TeletexString;break;case 21:a=xp.VideotexString;break;case 22:a=xp.IA5String;break;case 23:a=xp.UTCTime;break;case 24:a=xp.GeneralizedTime;break;case 25:a=xp.GraphicString;break;case 26:a=xp.VisibleString;break;case 27:a=xp.GeneralString;break;case 28:a=xp.UniversalString;break;case 29:a=xp.CharacterString;break;case 30:a=xp.BmpString;break;case 31:a=xp.DATE;break;case 32:a=xp.TimeOfDay;break;case 33:a=xp.DateTime;break;case 34:a=xp.Duration;break;default:{const e=i.idBlock.isConstructed?new xp.Constructed:new xp.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?xp.Constructed:xp.Primitive;return i=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,a),o=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:o,result:i}}function yy(e){if(!e.byteLength){const e=new Bp({},Ep);return e.error="Input buffer has zero length",{offset:-1,result:e}}return py(Hf.toUint8Array(e).slice(),0,e.byteLength)}function my(e,t){return e?1:t}Up=fy,xp.Primitive=Up,fy.NAME="PRIMITIVE";class by extends Ep{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=Hf.toUint8Array(e);if(!rp(this,s,t,r))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let i=t;for(;my(this.isIndefiniteForm,r)>0;){const e=py(s,i,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(i=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Ap)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Ap?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new sp;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?mp:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}by.NAME="ConstructedValueBlock";class Ay extends Bp{constructor(e={}){super(e,by),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Tp=Ay,xp.Constructed=Tp,Ay.NAME="CONSTRUCTED";class Iy extends Ep{fromBER(e,t,r){return t}toBER(e){return mp}}Iy.override="EndOfContentValueBlock";class vy extends Bp{constructor(e={}){super(e,Iy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Np=vy,xp.EndOfContent=Np,vy.NAME=Ap;class wy extends Bp{constructor(e={}){super(e,Ep),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Dp=wy,xp.Null=Dp,wy.NAME="NULL";class Sy extends(wp(Ep)){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=Hf.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=Hf.toUint8Array(e);return rp(this,s,t,r)?(this.valueHexView=s.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Xf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Sy.NAME="BooleanValueBlock";class Ey extends Bp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Sy),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Mp=Ey,xp.Boolean=Mp,Ey.NAME="BOOLEAN";class Cy extends(wp(by)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=by.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===Ap){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Ip)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,r),this.blockLength=r;return s}toBER(e,t){return this.isConstructed?by.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Cy.NAME="OctetStringValueBlock";class ky extends Bp{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Cy),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(s.byteLength){const e=py(s,0,s.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch{}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Ay.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${jf.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Pp&&e.push(t.valueBlock.valueHexView);return Hf.concat(e)}}Pp=ky,xp.OctetString=Pp,ky.NAME=Ip;class xy extends(wp(by)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let s=-1;if(this.isConstructed){if(s=by.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===Ap){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==vp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return s}const i=Hf.toUint8Array(e);if(!rp(this,i,t,r))return-1;const n=i.subarray(t,t+r);if(this.unusedBits=n[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=n.subarray(1);try{if(e.byteLength){const t=py(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch{}}return this.valueHexView=n.subarray(1),this.blockLength=n.length,t+r}toBER(e,t){if(this.isConstructed)return by.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return mp;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}xy.NAME="BitStringValueBlock";class By extends Bp{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},xy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ay.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function _y(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const o=n.length-1,a=i.slice(0),c=a.length-1;let l=0,h=0;for(let e=c<o?o:c;e>=0;e--,h++)l=1==h<a.length?n[o-h]+a[c-h]+r[0]:n[o-h]+r[0],r[0]=l/10,1==h>=n.length?n=Yf(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=Yf(r,n)),n}function Ry(e){if(e>=ip.length)for(let t=ip.length;t<=e;t++){const e=new Uint8Array([0]);let r=ip[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const s=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=s[0]/10,r[t]=s[0]%10}e[0]>0&&(r=Yf(e,r)),ip.push(r)}return ip[e]}function Oy(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),o=n.length-1,a=i.slice(0),c=a.length-1;let l,h=0;for(let e=c;e>=0;e--,h++)l=n[o-h]-a[c-h]-r,1==l<0?(r=1,n[o-h]=l+10):(r=0,n[o-h]=l);if(r>0)for(let e=o-c+1;e>=0;e--,h++){if(l=n[o-h]-r,!(l<0)){r=0,n[o-h]=l;break}r=1,n[o-h]=l+10}return n.slice()}Lp=By,xp.BitString=Lp,By.NAME=vp;class Uy extends(wp(Ep)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Xf.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let s=1;s<8;s++){if(t<=r){if(e<0){const e=Jf(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=Jf(t,8,s),n=new Uint8Array(i);if(128&n[0]){const e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),n=new Uint8Array(i);for(let r=0;r<e.byteLength;r++)n[r+1]=t[r];n[0]=0}return i}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,s=0){const i=this.fromBER(e,t,r);if(-1===i)return i;const n=this.valueHexView;return 0===n[0]&&128&n[1]?this.valueHexView=n.subarray(1):0!==s&&n.length<s&&(s-n.length>1&&(s=n.length+1),this.valueHexView=n.subarray(s-n.length)),i}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const s=super.fromBER(e,t,r);return-1===s||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),s=0;const i=this.valueHexView;let n="",o=!1;for(let o=i.byteLength-1;o>=0;o--){t=i[o];for(let i=0;i<8;i++)1&~t||(s===e?(r=Oy(Ry(s),r),n="-"):r=_y(r,Ry(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=np.charAt(r[e]));return!1===o&&(n+=np.charAt(0)),n}}Hp=Uy,Uy.NAME="IntegerValueBlock",Object.defineProperty(Hp.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Ty extends Bp{constructor(e={}){super(e,Uy),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ep(),BigInt(this.valueBlock.toString())}static fromBigInt(e){ep();const t=BigInt(e),r=new sp,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(jf.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${jf.ToHex(e)}`)+t,n=Hf.toUint8Array(jf.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Kp({valueHex:r.final()})}convertToDER(){const e=new Kp({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Kp({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Kp=Ty,xp.Integer=Kp,Ty.NAME="INTEGER";class Ny extends Ty{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Vp=Ny,xp.Enumerated=Vp,Ny.NAME="ENUMERATED";class Dy extends(wp(Ep)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const s=Hf.toUint8Array(e);if(!rp(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Wf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){ep();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=Jf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",mp;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r}toString(){let e="";if(this.isHexOnly)e=jf.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Dy.NAME="sidBlock";class My extends Ep{constructor({value:e=yp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Dy;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const s=this.value[r].toBER(e);if(0===s.byteLength)return this.error=this.value[r].error,mp;t.push(s)}return tp(t)}fromString(e){this.value=[];let t=0,r=0,s="",i=!1;do{if(r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1,i){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(s,10);if(isNaN(r))return;e.valueDec=r+t,i=!1}else{const e=new Dy;if(s>Number.MAX_SAFE_INTEGER){ep();const t=BigInt(s);e.valueBigInt=t}else if(e.valueDec=parseInt(s,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,this.value[r].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}My.NAME="ObjectIdentifierValueBlock";class Py extends Bp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,My),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Qp=Py,xp.ObjectIdentifier=Qp,Py.NAME="OBJECT IDENTIFIER";class Ly extends(wp(Sp)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=Hf.toUint8Array(e);if(!rp(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Wf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=Jf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",mp;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r.buffer}toString(){let e="";return e=this.isHexOnly?jf.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Ly.NAME="relativeSidBlock";class Hy extends Ep{constructor({value:e=yp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Ly;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const s=this.value[t].toBER(e);if(0===s.byteLength)return this.error=this.value[t].error,mp;r.push(s)}return tp(r)}fromString(e){this.value=[];let t=0,r=0,s="";do{r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1;const i=new Ly;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Hy.NAME="RelativeObjectIdentifierValueBlock";class Ky extends Bp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Hy),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Fp=Ky,xp.RelativeObjectIdentifier=Fp,Ky.NAME="RelativeObjectIdentifier";class Vy extends Ay{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Gp=Vy,xp.Sequence=Gp,Vy.NAME="SEQUENCE";class Qy extends Ay{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}$p=Qy,xp.Set=$p,Qy.NAME="SET";class Fy extends(wp(Ep)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=yp}toJSON(){return{...super.toJSON(),value:this.value}}}Fy.NAME="StringValueBlock";class Gy extends Fy{}Gy.NAME="SimpleStringValueBlock";class $y extends Rp{constructor({...e}={}){super(e,Gy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Hf.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);this.valueBlock.value=e}}$y.NAME="SIMPLE STRING";class jy extends $y{fromBuffer(e){this.valueBlock.valueHexView=Hf.toUint8Array(e);try{this.valueBlock.value=jf.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=jf.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(jf.FromUtf8String(e)),this.valueBlock.value=e}}jy.NAME="Utf8StringValueBlock";class qy extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}jp=qy,xp.Utf8String=jp,qy.NAME="UTF8String";class zy extends $y{fromBuffer(e){this.valueBlock.value=jf.ToUtf16String(e),this.valueBlock.valueHexView=Hf.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(jf.FromUtf16String(e))}}zy.NAME="BmpStringValueBlock";class Wy extends zy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}qp=Wy,xp.BmpString=qp,Wy.NAME="BMPString";class Jy extends $y{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let s=0;s<t;s++){const t=Jf(e.charCodeAt(s),8),i=new Uint8Array(t);if(i.length>4)continue;const n=4-i.length;for(let e=i.length-1;e>=0;e--)r[4*s+e+n]=i[e]}this.valueBlock.value=e}}Jy.NAME="UniversalStringValueBlock";class Yy extends Jy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}zp=Yy,xp.UniversalString=zp,Yy.NAME="UniversalString";class Xy extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Wp=Xy,xp.NumericString=Wp,Xy.NAME="NumericString";class Zy extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Jp=Zy,xp.PrintableString=Jp,Zy.NAME="PrintableString";class em extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Yp=em,xp.TeletexString=Yp,em.NAME="TeletexString";class tm extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Xp=tm,xp.VideotexString=Xp,tm.NAME="VideotexString";class rm extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Zp=rm,xp.IA5String=Zp,rm.NAME="IA5String";class sm extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}ey=sm,xp.GraphicString=ey,sm.NAME="GraphicString";class im extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ty=im,xp.VisibleString=ty,im.NAME="VisibleString";class nm extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}ry=nm,xp.GeneralString=ry,nm.NAME="GeneralString";class om extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}sy=om,xp.CharacterString=sy,om.NAME="CharacterString";class am extends im{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Hf.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=Zf(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Zf(this.month,2),e[2]=Zf(this.day,2),e[3]=Zf(this.hour,2),e[4]=Zf(this.minute,2),e[5]=Zf(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}iy=am,xp.UTCTime=iy,am.NAME="UTCTime";class cm extends am{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t,r=!1,s="",i="",n=0,o=0,a=0;if("Z"===e[e.length-1])s=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(r){if(-1!==s.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==s.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=s.indexOf("+"),r="";if(-1===t&&(t=s.indexOf("-"),e=-1),-1!==t){if(r=s.substring(t+1),s=s.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");a=e*i}}}let c=s.indexOf(".");if(-1===c&&(c=s.indexOf(",")),-1!==c){const e=new Number(`0${s.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");n=e.valueOf(),i=s.substring(0,c)}else i=s;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*n;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(i);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(Zf(this.year,4)),e.push(Zf(this.month,2)),e.push(Zf(this.day,2)),e.push(Zf(this.hour,2)),e.push(Zf(this.minute,2)),e.push(Zf(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(Zf(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}ny=cm,xp.GeneralizedTime=ny,cm.NAME="GeneralizedTime";class lm extends qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}oy=lm,xp.DATE=oy,lm.NAME="DATE";class hm extends qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ay=hm,xp.TimeOfDay=ay,hm.NAME="TimeOfDay";class um extends qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}cy=um,xp.DateTime=cy,um.NAME="DateTime";class dm extends qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}ly=dm,xp.Duration=ly,dm.NAME="Duration";class gm extends qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}hy=gm,xp.TIME=hy,gm.NAME="TIME";class fm{constructor({name:e=yp,optional:t=!1}={}){this.name=e,this.optional=t}}class pm extends fm{constructor({value:e=[],...t}={}){super(t),this.value=e}}class ym extends fm{constructor({value:e=new fm,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class mm{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Hf.toUint8Array(e)}constructor({data:e=bp}={}){this.dataView=Hf.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=Hf.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function bm(e,t,r){if(r instanceof pm){for(const s of r.value)if(bm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(op)&&(e.name=r.name),e}}if(r instanceof fm)return r.hasOwnProperty(op)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==0)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(lp in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(gp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(fp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.toBER(!1);if(0===s.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(s,0,s.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty(hp))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(up))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(dp))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(cp in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(ap in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=t.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:e};for(let t=0;t<s.length;t++)if(s[t]!==i[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&(e[r.name]=t)),r instanceof xp.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof ym&&(n=t.valueBlock.value.length),0===n)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){let t=!0;for(let e=0;e<r.valueBlock.value.length;e++)t=t&&(r.valueBlock.value[e].optional||!1);return t?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let o=0;o<n;o++)if(o-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[o].optional){const t={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof ym){if(i=bm(e,t.valueBlock.value[o],r.valueBlock.value[0].value),!1===i.verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&delete e[r.name]),i;s++}if(op in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=pp in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e,void 0===s[r.valueBlock.value[0].name]&&(s[r.valueBlock.value[0].name]=[]),s[r.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=bm(e,t.valueBlock.value[o-s],r.valueBlock.value[o]),!1===i.verified){if(!r.valueBlock.value[o].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&delete e[r.name]),i;s++}if(!1===i.verified){const t={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&ap in t.valueBlock){const s=py(t.valueBlock.valueHexView);if(-1===s.offset){const t={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,yp),r.name&&(delete e[r.name],t.name=r.name)),t}return bm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function Am(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=py(Hf.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:bm(r.result,r.result,t)}(gy=uy||(uy={}))[gy.Sequence=0]="Sequence",gy[gy.Set=1]="Set",gy[gy.Choice=2]="Choice",function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(dy||(dy={}));class Im{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Hf.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Hf.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof By))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new By({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new By({name:e})}toNumber(){let e="";const t=new Uint8Array(this.value);for(const r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2);const r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;const s=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");let i=0;for(;i<r;)s[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=s.buffer}}class vm{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Hf.isBufferSource(e)?this.buffer=Hf.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof ky))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new ky({valueHex:this.buffer})}toSchema(e){return new ky({name:e})}}const wm={fromASN:e=>e instanceof wy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new wy;const t=yy(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Sm={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Ty({value:+e})},Em={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Ny({value:e})},Cm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Ty({valueHex:e})},km={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new By({valueHex:e})},xm={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Py({value:e})},Bm={fromASN:e=>e.valueBlock.value,toASN:e=>new Ey({value:e})},_m={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new ky({valueHex:e})},Rm={fromASN:e=>new vm(e.getValue()),toASN:e=>e.toASN()};function Om(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const Um=Om(qy),Tm=Om(Wy),Nm=Om(Yy),Dm=Om(Xy),Mm=Om(Zy),Pm=Om(em),Lm=Om(tm),Hm=Om(rm),Km=Om(sm),Vm=Om(im),Qm=Om(nm),Fm=Om(om),Gm={fromASN:e=>e.toDate(),toASN:e=>new am({valueDate:e})},$m={fromASN:e=>e.toDate(),toASN:e=>new cm({valueDate:e})},jm={fromASN:()=>null,toASN:()=>new wy};function qm(e){switch(e){case dy.Any:return wm;case dy.BitString:return km;case dy.BmpString:return Tm;case dy.Boolean:return Bm;case dy.CharacterString:return Fm;case dy.Enumerated:return Em;case dy.GeneralString:return Qm;case dy.GeneralizedTime:return $m;case dy.GraphicString:return Km;case dy.IA5String:return Hm;case dy.Integer:return Sm;case dy.Null:return jm;case dy.NumericString:return Dm;case dy.ObjectIdentifier:return xm;case dy.OctetString:return _m;case dy.PrintableString:return Mm;case dy.TeletexString:return Pm;case dy.UTCTime:return Gm;case dy.UniversalString:return Nm;case dy.Utf8String:return Um;case dy.VideotexString:return Lm;case dy.VisibleString:return Vm;default:return null}}function zm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||zm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Wm(e){var t;if(e){const r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||Wm(r)}return!1}function Jm(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}const Ym=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){const t={type:uy.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){const r=this.items.get(e)||this.createDefault(e),s=[];for(const e in r.items){const i=r.items[e],n=t?e:"";let o;if("number"==typeof i.type){const e=dy[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else zm(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===uy.Choice?o=new fm({name:n}):(o=this.create(i.type,!1),o.name=n):o=new fm({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?Qy:Vy)({name:"",value:[new ym({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||zm(i.type)){const e=i.repeated?Ay:fy;s.push(new e({name:n,optional:c,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const e=!!i.repeated;let t=e?o:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new Ay({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new Ay({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case uy.Sequence:return new Vy({value:s,name:""});case uy.Set:return new Qy({value:s,name:""});case uy.Choice:return new pm({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},Xm=e=>t=>{let r;Ym.has(t)?r=Ym.get(t):(r=Ym.createDefault(t),Ym.set(t,r)),Object.assign(r,e)},Zm=e=>(t,r)=>{let s;Ym.has(t.constructor)?s=Ym.get(t.constructor):(s=Ym.createDefault(t.constructor),Ym.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=qm(e.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);i.converter=s}s.items[r]=i};class eb extends Error{constructor(){super(...arguments),this.schemas=[]}}class tb{static parse(e,t){const r=yy(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r;try{if(zm(t))return(new t).fromASN(e);const s=Ym.get(t);Ym.cache(t);let i=s.schema;if(e.constructor===Ay&&s.type!==uy.Choice){i=new Ay({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=bm({},e,i);if(!n.verified)throw new eb(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(Wm(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const r=s.itemType;if("number"==typeof r){const s=qm(r);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,e=>s.fromASN(e))}return t.from(e.valueBlock.value,e=>this.fromASN(e,r))}for(const e in s.items){const t=n.result[e];if(!t)continue;const i=s.items[e],c=i.type;if("number"==typeof c||zm(c)){const s=null!==(r=i.converter)&&void 0!==r?r:zm(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?Vy:Qy);r.valueBlock=t.valueBlock;const n=yy(r.toBER(!1));if(-1===n.offset)throw new Error(`Cannot parse the child item. ${n.result.error}`);if(!("value"in n.result.valueBlock)||!Array.isArray(n.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const a=n.result.valueBlock.value;o[e]=Array.from(a,e=>s.fromASN(e))}else o[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(zm(c))e=(new c).toSchema("");else{const t=dy[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=yy(e.toBER(!1)).result}o[e]=s.fromASN(r)}}else if(i.repeated){if(!Array.isArray(t))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");o[e]=Array.from(t,e=>this.fromASN(e,c))}else o[e]=this.fromASN(t,c)}return o}catch(e){throw e instanceof eb&&e.schemas.push(t.name),e}}}class rb{static serialize(e){return e instanceof Bp?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&zm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=Ym.get(t);Ym.cache(t);let s,i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){const s=qm(r.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);i=e.map(e=>s.toASN(e))}else i=e.map(e=>this.toAsnItem({type:r.itemType},"[]",t,e))}else for(const s in r.items){const n=r.items[s],o=e[s];if(void 0===o||n.defaultValue===o||"object"==typeof n.defaultValue&&"object"==typeof o&&Jm(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=rb.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!zm(n.type))i.push(new Ay({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof wy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new fy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Ay({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[a]}));else n.repeated?i=i.concat(a):i.push(a)}switch(r.type){case uy.Sequence:s=new Vy({value:i});break;case uy.Set:s=new Qy({value:i});break;case uy.Choice:if(!i[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);s=i[0]}return s}static toAsnItem(e,t,r,s){let i;if("number"==typeof e.type){const n=e.converter;if(!n)throw new Error(`Property '${t}' doesn't have converter for type ${dy[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>n.toASN(e));i=new("sequence"===e.repeated?Vy:Qy)({value:t})}else i=n.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>this.toASN(e));i=new("sequence"===e.repeated?Vy:Qy)({value:t})}else i=this.toASN(s);return i}}class sb extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class ib{static serialize(e){return rb.serialize(e)}static parse(e,t){return tb.parse(e,t)}static toString(e){const t=yy(Hf.isBufferSource(e)?Hf.toArrayBuffer(e):ib.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function nb(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class ob extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class ab extends ob{constructor(e,t,r){super(t,r),this.schema=e}}class cb extends ab{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class lb extends ob{}class hb extends ob{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class ub extends cb{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var db;function gb(e,t){if(!function(e,t){switch(t){case db.Boolean:return"boolean"==typeof e;case db.Number:return"number"==typeof e;case db.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${db[t]}`)}function fb(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||fb(e.prototype):!!(e&&e.toJSON&&e.fromJSON)}!function(e){e[e.Any=0]="Any",e[e.Boolean=1]="Boolean",e[e.Number=2]="Number",e[e.String=3]="String"}(db||(db={}));const pb="default",yb=new class{constructor(){this.items=new Map}has(e){return this.items.has(e)||!!this.findParentSchema(e)}get(e){const t=this.items.get(e)||this.findParentSchema(e);if(!t)throw new Error("Cannot get schema for current target");return t}create(e){const t={names:{}},r=this.findParentSchema(e);if(r){Object.assign(t,r),t.names={};for(const e in r.names)t.names[e]=Object.assign({},r.names[e])}return t.target=e,t}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=e.__proto__;return t?this.items.get(t)||this.findParentSchema(t):null}};class mb{constructor(e){this.pattern=new RegExp(e)}validate(e){const t=new RegExp(this.pattern.source,this.pattern.flags);if("string"!=typeof e)throw new lb("Incoming value must be string");if(!t.exec(e))throw new lb(`Value doesn't match to pattern '${t.toString()}'`)}}class bb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(gb(e,db.Number),!(this.min<=e&&e<=this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new lb(`Value doesn't match to diapason [${e},${t}]`)}}}class Ab{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(gb(e,db.Number),!(this.min<e&&e<this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new lb(`Value doesn't match to diapason (${e},${t})`)}}}class Ib{constructor(e,t,r){this.length=e,this.minLength=t,this.maxLength=r}validate(e){if(void 0===this.length){if(void 0!==this.minLength&&e.length<this.minLength)throw new lb(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new lb(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new lb(`Value length must be exactly ${this.length}.`)}}class vb{constructor(e){this.enumeration=e}validate(e){if(gb(e,db.String),!this.enumeration.includes(e))throw new lb(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class wb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Ib&&t.repeated?r.validate(e):r.validate(s)}static checkTypes(e,t){if(t.repeated&&!Array.isArray(e))throw new TypeError("Value must be Array");if("number"==typeof t.type){const r=Array.isArray(e)?e:[e];for(const e of r)gb(e,t.type)}}static getSchemaByName(e,t=pb){return{...e.names[pb],...e.names[t]}}}class Sb extends wb{static serialize(e,t,r,s){const i=this.toJSON(e,t);return JSON.stringify(i,r,s)}static toJSON(e,t={}){let r,s=t.targetSchema;const i=t.schemaName||pb;if(fb(e))return e.toJSON();if(Array.isArray(e)){r=[];for(const s of e)r.push(this.toJSON(s,t))}else if("object"==typeof e){if(s&&!yb.has(s))throw new ob("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,yb.has(s)){const t=yb.get(s);r={};const n=this.getSchemaByName(t,i);for(const o in n)try{const t=n[o],a=e[o];let c;if(t.optional&&void 0===a||void 0!==t.defaultValue&&a===t.defaultValue)continue;if(!t.optional&&void 0===a)throw new hb(s.name,`Property '${o}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?a.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(a,e):a:t.repeated?a.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(a,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||o]=c}catch(e){throw e instanceof hb?e:new hb(t.target.name,`Property '${o}' is wrong. ${e.message}`,e)}}else{r={};for(const t in e)r[t]=this.toJSON(e[t],{schemaName:i})}}else r=e;return r}}class Eb extends wb{static parse(e,t){const r=JSON.parse(e);return this.fromJSON(r,t)}static fromJSON(e,t){const r=t.targetSchema,s=t.schemaName||pb,i=new r;if(fb(i))return i.fromJSON(e);const n=yb.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&Eb.checkStrictProperty(e,o,n);for(const r in o)try{const a=o[r],c=a.name||r,l=e[c];if(void 0===l&&(a.optional||void 0!==a.defaultValue))continue;if(!a.optional&&void 0===l)throw new cb(n,`Property '${c}' is required.`);if(this.checkTypes(l,a),this.checkValues(l,a),"number"==typeof a.type)a.converter?a.repeated?i[r]=l.map(e=>a.converter.fromJSON(e,i)):i[r]=a.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:a.type,schemaName:s};a.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof cb||(e=new cb(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;a[r]=e}const c=Object.keys(a);if(c.length)throw new ub(n,c,a);return i}static checkStrictProperty(e,t,r){const s=Object.keys(e),i=Object.keys(t),n=[];for(const e of s)-1===i.indexOf(e)&&n.push(e);if(n.length)throw new ub(r,n)}}const Cb=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;yb.has(t.constructor)?(i=yb.get(t.constructor),i.target!==t.constructor&&(i=yb.create(t.constructor),yb.set(t.constructor,i))):(i=yb.create(t.constructor),yb.set(t.constructor,i));const n={type:db.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new mb(e.pattern)),e.type!==db.Number&&e.type!==db.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new bb(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new Ab(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new vb(e.enumeration))),(e.type===db.String||e.repeated||e.type===db.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Ib(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!yb.has(o.type)&&!fb(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||pb];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class kb extends Error{}class xb extends kb{}class Bb extends kb{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class _b extends kb{}class Rb extends kb{constructor(e){super(`${e}: Missing required property`)}}class Ob{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return jf.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=jf.ToBase64(e);let s,i=0;const n=[];for(;i<r.length&&(s=r.slice(i,i+64),s.length);)n.push(s),i+=64;const o=t.toUpperCase();return`-----BEGIN ${o}-----\n${n.join("\n")}\n-----END ${o}-----`}static isPEM(e){return/-----BEGIN .+-----[A-Za-z0-9+/+=\s\n]+-----END .+-----/i.test(e)}static getTagName(e){if(!this.isPEM(e))throw new Error("Bad parameter. Incoming data is not right PEM");const t=/-----BEGIN (.+)-----/.exec(e);if(!t)throw new Error("Cannot get tag from PEM");return t[1]}static hasTagName(e,t){const r=this.getTagName(e);return t.toLowerCase()===r.toLowerCase()}static isCertificate(e){return this.hasTagName(e,"certificate")}static isCertificateRequest(e){return this.hasTagName(e,"certificate request")}static isCRL(e){return this.hasTagName(e,"x509 crl")}static isPublicKey(e){return this.hasTagName(e,"public key")}}class Ub{async digest(...e){return this.checkDigest.apply(this,e),this.onDigest.apply(this,e)}checkDigest(e,t){this.checkAlgorithmName(e)}async onDigest(e,t){throw new Bb("digest")}async generateKey(...e){return this.checkGenerateKey.apply(this,e),this.onGenerateKey.apply(this,e)}checkGenerateKey(e,t,r,...s){if(this.checkAlgorithmName(e),this.checkGenerateKeyParams(e),!r||!r.length)throw new TypeError("Usages cannot be empty when creating a key.");let i;i=Array.isArray(this.usages)?this.usages:this.usages.privateKey.concat(this.usages.publicKey),this.checkKeyUsages(r,i)}checkGenerateKeyParams(e){}async onGenerateKey(e,t,r,...s){throw new Bb("generateKey")}async sign(...e){return this.checkSign.apply(this,e),this.onSign.apply(this,e)}checkSign(e,t,r,...s){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"sign")}async onSign(e,t,r,...s){throw new Bb("sign")}async verify(...e){return this.checkVerify.apply(this,e),this.onVerify.apply(this,e)}checkVerify(e,t,r,s,...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"verify")}async onVerify(e,t,r,s,...i){throw new Bb("verify")}async encrypt(...e){return this.checkEncrypt.apply(this,e),this.onEncrypt.apply(this,e)}checkEncrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"encrypt":void 0)}async onEncrypt(e,t,r,...s){throw new Bb("encrypt")}async decrypt(...e){return this.checkDecrypt.apply(this,e),this.onDecrypt.apply(this,e)}checkDecrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"decrypt":void 0)}async onDecrypt(e,t,r,...s){throw new Bb("decrypt")}async deriveBits(...e){return this.checkDeriveBits.apply(this,e),this.onDeriveBits.apply(this,e)}checkDeriveBits(e,t,r,s={},...i){if(this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"deriveBits":void 0),r%8!=0)throw new _b("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new Bb("deriveBits")}async exportKey(...e){return this.checkExportKey.apply(this,e),this.onExportKey.apply(this,e)}checkExportKey(e,t,...r){if(this.checkKeyFormat(e),this.checkCryptoKey(t),!t.extractable)throw new kb("key: Is not extractable")}async onExportKey(e,t,...r){throw new Bb("exportKey")}async importKey(...e){return this.checkImportKey.apply(this,e),this.onImportKey.apply(this,e)}checkImportKey(e,t,r,s,i,...n){this.checkKeyFormat(e),this.checkKeyData(e,t),this.checkAlgorithmName(r),this.checkImportParams(r),Array.isArray(this.usages)&&this.checkKeyUsages(i,this.usages)}async onImportKey(e,t,r,s,i,...n){throw new Bb("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new xb("Unrecognized name")}checkAlgorithmParams(e){}checkDerivedKeyParams(e){}checkKeyUsages(e,t){for(const r of e)if(-1===t.indexOf(r))throw new TypeError("Cannot create a key using the specified key usages")}checkCryptoKey(e,t){if(this.checkAlgorithmName(e.algorithm),t&&-1===e.usages.indexOf(t))throw new kb("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new Rb(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new _b(`hash: Must be one of ${t.join(", ")}`)}checkImportParams(e){}checkKeyFormat(e){switch(e){case"raw":case"pkcs8":case"spki":case"jwk":break;default:throw new TypeError("format: Is invalid value. Must be 'jwk', 'raw', 'spki', or 'pkcs8'")}}checkKeyData(e,t){if(!t)throw new TypeError("keyData: Cannot be empty on empty on key importing");if("jwk"===e){if("object"!=typeof(r=t)||!("kty"in r))throw new TypeError("keyData: Is not JsonWebToken")}else if(!Hf.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return Hf.toArrayBuffer(e)}}class Tb extends Ub{checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");switch(e.length){case 128:case 192:case 256:break;default:throw new TypeError("length: Must be 128, 192, or 256")}}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Nb extends Tb{constructor(){super(...arguments),this.name="AES-CBC",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.iv.byteLength)throw new TypeError("iv: Must have length 16 bytes")}}class Db extends Tb{constructor(){super(...arguments),this.name="AES-CMAC",this.usages=["sign","verify"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new _b("length: Must be more than 0")}}class Mb extends Tb{constructor(){super(...arguments),this.name="AES-CTR",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"counter"),!(e.counter instanceof ArrayBuffer||ArrayBuffer.isView(e.counter)))throw new TypeError("counter: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.counter.byteLength)throw new TypeError("iv: Must have length 16 bytes");if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new _b("length: Must be more than 0")}}class Pb extends Tb{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Lb extends Tb{constructor(){super(...arguments),this.name="AES-GCM",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){var t;if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength<1)throw new _b("iv: Must have length more than 0 and less than 2^64 - 1");switch(null!==(t=e.tagLength)&&void 0!==t||(e.tagLength=128),e.tagLength){case 32:case 64:case 96:case 104:case 112:case 120:case 128:break;default:throw new _b("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class Hb extends Tb{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class Kb extends Ub{constructor(){super(...arguments),this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.ivSize){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength!==this.ivSize)throw new TypeError(`iv: Must have length ${this.ivSize} bytes`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");if(e.length!==this.keySizeBits)throw new _b(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Vb extends Ub{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"]}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=jf.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");if(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength%8||e.modulusLength<256||e.modulusLength>16384)throw new TypeError("The modulus length must be a multiple of 8 bits and >= 256 and <= 16384")}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class Qb extends Vb{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Fb extends Vb{constructor(){super(...arguments),this.name="RSA-PSS",this.usages={privateKey:["sign"],publicKey:["verify"]}}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"saltLength"),"number"!=typeof e.saltLength)throw new TypeError("saltLength: Is not a Number");if(e.saltLength<0)throw new RangeError("saltLength: Must be positive number")}}class Gb extends Vb{constructor(){super(...arguments),this.name="RSA-OAEP",this.usages={privateKey:["decrypt","unwrapKey"],publicKey:["encrypt","wrapKey"]}}checkAlgorithmParams(e){if(e.label&&!(e.label instanceof ArrayBuffer||ArrayBuffer.isView(e.label)))throw new TypeError("label: Is not of type '(ArrayBuffer or ArrayBufferView)'")}}class $b extends Ub{checkGenerateKeyParams(e){this.checkRequiredProperty(e,"namedCurve"),this.checkNamedCurve(e.namedCurve)}checkNamedCurve(e){for(const t of this.namedCurves)if(t.toLowerCase()===e.toLowerCase())return;throw new _b(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class jb extends $b{constructor(){super(...arguments),this.name="ECDSA",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}const qb=["secret","private","public"];class zb{static create(e,t,r,s){const i=new this;return i.algorithm=e,i.type=t,i.extractable=r,i.usages=s,i}static isKeyType(e){return-1!==qb.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class Wb extends $b{constructor(){super(...arguments),this.name="ECDH",this.usages={privateKey:["deriveBits","deriveKey"],publicKey:[]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"public"),!(e.public instanceof zb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new _b("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new _b(`public: Is not ${this.name} key`)}}class Jb extends Wb{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class Yb extends $b{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Xb=class{constructor(e){e&&(this.value=e)}};nb([Zm({type:dy.ObjectIdentifier})],Xb.prototype,"value",void 0),Xb=nb([Xm({type:uy.Choice})],Xb);class Zb{constructor(e){Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Zb.prototype,"algorithm",void 0),nb([Zm({type:dy.Any,optional:!0})],Zb.prototype,"parameters",void 0);class eA{constructor(){this.version=0,this.privateKeyAlgorithm=new Zb,this.privateKey=new ArrayBuffer(0)}}nb([Zm({type:dy.Integer})],eA.prototype,"version",void 0),nb([Zm({type:Zb})],eA.prototype,"privateKeyAlgorithm",void 0),nb([Zm({type:dy.OctetString})],eA.prototype,"privateKey",void 0),nb([Zm({type:dy.Any,optional:!0})],eA.prototype,"attributes",void 0);class tA{constructor(){this.publicKeyAlgorithm=new Zb,this.publicKey=new ArrayBuffer(0)}}nb([Zm({type:Zb})],tA.prototype,"publicKeyAlgorithm",void 0),nb([Zm({type:dy.BitString})],tA.prototype,"publicKey",void 0);const rA={fromJSON:e=>jf.FromBase64Url(e),toJSON:e=>jf.ToBase64Url(new Uint8Array(e))},sA={fromASN:e=>{const t=e.valueBlock.valueHex;return new Uint8Array(t)[0]?e.valueBlock.valueHex:e.valueBlock.valueHex.slice(1)},toASN:e=>{const t=new Uint8Array(e)[0]>127?qf(new Uint8Array([0]).buffer,e):e;return new Ty({valueHex:t})}};class iA{constructor(){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0)}}nb([Zm({type:dy.Integer,converter:Sm})],iA.prototype,"version",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"n",converter:rA})],iA.prototype,"modulus",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"e",converter:rA})],iA.prototype,"publicExponent",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"d",converter:rA})],iA.prototype,"privateExponent",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"p",converter:rA})],iA.prototype,"prime1",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"q",converter:rA})],iA.prototype,"prime2",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"dp",converter:rA})],iA.prototype,"exponent1",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"dq",converter:rA})],iA.prototype,"exponent2",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"qi",converter:rA})],iA.prototype,"coefficient",void 0),nb([Zm({type:dy.Any,optional:!0})],iA.prototype,"otherPrimeInfos",void 0);class nA{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"n",converter:rA})],nA.prototype,"modulus",void 0),nb([Zm({type:dy.Integer,converter:sA}),Cb({name:"e",converter:rA})],nA.prototype,"publicExponent",void 0);let oA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){let e=new Uint8Array(this.value);if(4!==e[0])throw new kb("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:jf.ToBase64Url(e.buffer.slice(0,0+t)),y:jf.ToBase64Url(e.buffer.slice(0+t,0+t+t))}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");if(!("y"in e))throw new Error("y: Missing required property");const t=jf.FromBase64Url(e.x),r=jf.FromBase64Url(e.y),s=qf(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};nb([Zm({type:dy.OctetString})],oA.prototype,"value",void 0),oA=nb([Xm({type:uy.Choice})],oA);class aA{constructor(){this.version=1,this.privateKey=new ArrayBuffer(0)}fromJSON(e){if(!("d"in e))throw new Error("d: Missing required property");if(this.privateKey=jf.FromBase64Url(e.d),"x"in e){const t=new oA;t.fromJSON(e);const r=rb.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=jf.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new oA(this.publicKey).toJSON()),e}}nb([Zm({type:dy.Integer,converter:Sm})],aA.prototype,"version",void 0),nb([Zm({type:dy.OctetString})],aA.prototype,"privateKey",void 0),nb([Zm({context:0,type:dy.Any,optional:!0})],aA.prototype,"parameters",void 0),nb([Zm({context:1,type:dy.BitString,optional:!0})],aA.prototype,"publicKey",void 0);const cA={fromASN:e=>{const t=new Uint8Array(e.valueBlock.valueHex);return 0===t[0]?t.buffer.slice(1):t.buffer},toASN:e=>{const t=new Uint8Array(e);if(t[0]>127){const e=new Uint8Array(t.length+1);return e.set(t,1),new Ty({valueHex:e.buffer})}return new Ty({valueHex:e})}};var lA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:cA});class hA{static decodePoint(e,t){const r=Hf.toUint8Array(e);if(0===r.length||4!==r[0])throw new Error("Only uncompressed point format supported");const s=(r.length-1)/2;if(s!==Math.ceil(t/8))throw new Error("Point does not match field size");return{x:r.slice(1,s+1),y:r.slice(s+1,s+1+s)}}static encodePoint(e,t){const r=Math.ceil(t/8);if(e.x.byteLength!==r||e.y.byteLength!==r)throw new Error("X,Y coordinates don't match point size criteria");const s=Hf.toUint8Array(e.x),i=Hf.toUint8Array(e.y),n=new Uint8Array(2*r+1);return n[0]=4,n.set(s,1),n.set(i,r+1),n}static getSize(e){return Math.ceil(e/8)}static encodeSignature(e,t){const r=this.getSize(t),s=Hf.toUint8Array(e.r),i=Hf.toUint8Array(e.s),n=new Uint8Array(2*r);return n.set(this.padStart(s,r)),n.set(this.padStart(i,r),r),n}static decodeSignature(e,t){const r=this.getSize(t),s=Hf.toUint8Array(e);if(s.length!==2*r)throw new Error("Incorrect size of the signature");const i=s.slice(0,r),n=s.slice(r);return{r:this.trimStart(i),s:this.trimStart(n)}}static trimStart(e){let t=0;for(;t<e.length-1&&0===e[t];)t++;return 0===t?e:e.slice(t,e.length)}static padStart(e,t){if(t===e.length)return e;const r=new Uint8Array(t);return r.set(e,t-e.length),r}}class uA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=hA.decodeSignature(e,8*t),s=new uA;return s.r=Hf.toArrayBuffer(r.r),s.s=Hf.toArrayBuffer(r.s),s}toWebCryptoSignature(e){if(!e){const t=Math.max(this.r.byteLength,this.s.byteLength);e=t<=32?256:t<=48?384:521}return hA.encodeSignature(this,e).buffer}}nb([Zm({type:dy.Integer,converter:cA})],uA.prototype,"r",void 0),nb([Zm({type:dy.Integer,converter:cA})],uA.prototype,"s",void 0);class dA extends eA{}nb([Zm({context:1,implicit:!0,type:dy.BitString,optional:!0})],dA.prototype,"publicKey",void 0);let gA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=jf.FromBase64Url(e.d),this}toJSON(){return{d:jf.ToBase64Url(this.value)}}};nb([Zm({type:dy.OctetString})],gA.prototype,"value",void 0),gA=nb([Xm({type:uy.Choice})],gA);let fA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:jf.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=jf.FromBase64Url(e.x),this}};nb([Zm({type:dy.BitString})],fA.prototype,"value",void 0),fA=nb([Xm({type:uy.Choice})],fA);let pA=class{};nb([Zm({type:dy.OctetString}),Cb({type:db.String,converter:rA})],pA.prototype,"d",void 0),pA=nb([Xm({type:uy.Choice})],pA);const yA="1.2.840.10045.3.1.7",mA="1.3.132.0",bA=`${mA}.34`,AA=`${mA}.35`,IA=`${mA}.10`,vA="1.3.36.3.3.2.8.1.1",wA=`${vA}.1`,SA=`${vA}.2`,EA=`${vA}.3`,CA=`${vA}.4`,kA=`${vA}.5`,xA=`${vA}.6`,BA=`${vA}.7`,_A=`${vA}.8`,RA=`${vA}.9`,OA=`${vA}.10`,UA=`${vA}.11`,TA=`${vA}.12`,NA=`${vA}.13`,DA=`${vA}.14`;var MA=Object.freeze({__proto__:null,AlgorithmIdentifier:Zb,get CurvePrivateKey(){return pA},EcDsaSignature:uA,EcPrivateKey:aA,get EcPublicKey(){return oA},get EdPrivateKey(){return gA},get EdPublicKey(){return fA},get ObjectIdentifier(){return Xb},OneAsymmetricKey:dA,PrivateKeyInfo:eA,PublicKeyInfo:tA,RsaPrivateKey:iA,RsaPublicKey:nA,converters:lA,idBrainpoolP160r1:wA,idBrainpoolP160t1:SA,idBrainpoolP192r1:EA,idBrainpoolP192t1:CA,idBrainpoolP224r1:kA,idBrainpoolP224t1:xA,idBrainpoolP256r1:BA,idBrainpoolP256t1:_A,idBrainpoolP320r1:RA,idBrainpoolP320t1:OA,idBrainpoolP384r1:UA,idBrainpoolP384t1:TA,idBrainpoolP512r1:NA,idBrainpoolP512t1:DA,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:mA,idSecp256k1:IA,idSecp256r1:yA,idSecp384r1:bA,idSecp521r1:AA,idVersionOne:vA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class PA{constructor(){}static register(e){const t=new Xb;t.value=e.id;const r=ib.serialize(t);this.items.push({...e,raw:r}),this.names.push(e.name)}static find(e){e=e.toUpperCase();for(const t of this.items)if(t.name.toUpperCase()===e||t.id.toUpperCase()===e)return t;return null}static get(e){const t=this.find(e);if(!t)throw new Error(`Unsupported EC named curve '${e}'`);return t}}PA.items=[],PA.names=[],PA.register({name:"P-256",id:yA,size:256}),PA.register({name:"P-384",id:bA,size:384}),PA.register({name:"P-521",id:AA,size:521}),PA.register({name:"K-256",id:IA,size:256}),PA.register({name:"brainpoolP160r1",id:wA,size:160}),PA.register({name:"brainpoolP160t1",id:SA,size:160}),PA.register({name:"brainpoolP192r1",id:EA,size:192}),PA.register({name:"brainpoolP192t1",id:CA,size:192}),PA.register({name:"brainpoolP224r1",id:kA,size:224}),PA.register({name:"brainpoolP224t1",id:xA,size:224}),PA.register({name:"brainpoolP256r1",id:BA,size:256}),PA.register({name:"brainpoolP256t1",id:_A,size:256}),PA.register({name:"brainpoolP320r1",id:RA,size:320}),PA.register({name:"brainpoolP320t1",id:OA,size:320}),PA.register({name:"brainpoolP384r1",id:UA,size:384}),PA.register({name:"brainpoolP384t1",id:TA,size:384}),PA.register({name:"brainpoolP512r1",id:NA,size:512}),PA.register({name:"brainpoolP512t1",id:DA,size:512});class LA extends Ub{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class HA extends Ub{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class KA extends Ub{constructor(){super(...arguments),this.name="HMAC",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["sign","verify"]}getDefaultLength(e){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":return 512;default:throw new Error(`Unknown algorithm name '${e}'`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),"length"in e){if("number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new RangeError("length: Number is out of range")}}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class VA extends Ub{constructor(){super(...arguments),this.name="PBKDF2",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveBits","deriveKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!(e.salt instanceof ArrayBuffer||ArrayBuffer.isView(e.salt)))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"iterations"),"number"!=typeof e.iterations)throw new TypeError("iterations: Is not a Number");if(e.iterations<1)throw new TypeError("iterations: Is less than 1")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class QA extends Ub{constructor(){super(...arguments),this.name="HKDF",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveKey","deriveBits"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!Hf.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!Hf.isBufferSource(e.info))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class FA extends Ub{constructor(){super(...arguments),this.usages=[],this.defaultLength=0}digest(...e){return e[0]={length:this.defaultLength,...e[0]},super.digest.apply(this,e)}checkDigest(e,t){super.checkDigest(e,t);const r=e.length||0;if("number"!=typeof r)throw new TypeError("length: Is not a Number");if(r<0)throw new TypeError("length: Is negative")}}class GA extends FA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class $A extends FA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class jA{get[Symbol.toStringTag](){return"Crypto"}randomUUID(){const e=this.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=jf.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class qA{constructor(){this.items={}}get(e){return this.items[e.toLowerCase()]||null}set(e){this.items[e.name.toLowerCase()]=e}removeAt(e){const t=this.get(e.toLowerCase());return t&&delete this.items[e],t}has(e){return!!this.get(e)}get length(){return Object.keys(this.items).length}get algorithms(){const e=[];for(const t in this.items){const r=this.items[t];e.push(r.name)}return e.sort()}}const zA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},WA=["pkcs8","spki","raw"];class JA{constructor(){this.providers=new qA}static isHashedAlgorithm(e){return!!(e&&"object"==typeof e&&"name"in e&&"hash"in e)}get[Symbol.toStringTag](){return"SubtleCrypto"}async digest(...e){this.checkRequiredArguments(e,2,"digest");const[t,r,...s]=e,i=this.prepareAlgorithm(t),n=Hf.toArrayBuffer(r),o=this.getProvider(i.name);return await o.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.generateKey({...n,name:o.name},r,s,...i)}async sign(...e){this.checkRequiredArguments(e,3,"sign");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Hf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.sign({...n,name:a.name},r,o,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const o=this.prepareAlgorithm(t),a=Hf.toArrayBuffer(i),c=Hf.toArrayBuffer(s),l=this.getProvider(o.name);return await l.verify({...o,name:l.name},r,c,a,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Hf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.encrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async decrypt(...e){this.checkRequiredArguments(e,3,"decrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Hf.toArrayBuffer(s),a=this.getProvider(n.name);return await a.decrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async deriveBits(...e){this.checkRequiredArguments(e,3,"deriveBits");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.deriveBits({...n,name:o.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s);this.getProvider(a.name).checkDerivedKeyParams(a);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const h=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...o);return this.importKey("raw",h,s,i,n,...o)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!zA[t])throw new TypeError("Invalid keyFormat argument");if(!zA[t].includes(r.type))throw new DOMException("The key is not of the expected type");const i=this.getProvider(r.algorithm.name);return await i.exportKey(t,r,...s)}async importKey(...e){this.checkRequiredArguments(e,5,"importKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s),c=this.getProvider(a.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!WA.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!Hf.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...a,name:c.name},i,n,...o)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=jf.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=Hf.toArrayBuffer(n),c=this.getProvider(o.name);return c.encrypt({...o,name:c.name},r,a,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,o,...a){const c=this.prepareAlgorithm(s),l=Hf.toArrayBuffer(t),h=this.getProvider(c.name);let u=await h.decrypt({...c,name:h.name},r,l,{keyUsage:!1},...a);if("jwk"===e)try{u=JSON.parse(jf.ToUtf8String(u))}catch(e){const t=new TypeError("wrappedKey: Is not a JSON");throw t.internal=e,t}return this.importKey(e,u,i,n,o,...a)}checkRequiredArguments(e,t,r){if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'SubtleCrypto': ${t} arguments required, but only ${e.length} present`)}prepareAlgorithm(e){if("string"==typeof e)return{name:e};if(JA.isHashedAlgorithm(e)){const t={...e};return t.hash=this.prepareAlgorithm(e.hash),t}return{...e}}getProvider(e){const t=this.providers.get(e);if(!t)throw new xb("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof zb))throw new TypeError("Key is not of type 'CryptoKey'")}}const YA=t(import.meta.url)("buffer"),XA=t(import.meta.url)("crypto");var ZA=o.n(XA);const eI=t(import.meta.url)("process"),tI={fromJSON:e=>YA.Buffer.from(jf.FromBase64Url(e)),toJSON:e=>jf.ToBase64Url(e)};class rI extends zb{constructor(){super(...arguments),this.data=YA.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}nb([Cb({name:"ext",type:db.Boolean,optional:!0})],rI.prototype,"extractable",void 0),nb([Cb({name:"key_ops",type:db.String,repeated:!0,optional:!0})],rI.prototype,"usages",void 0),nb([Cb({type:db.String})],rI.prototype,"kty",void 0),nb([Cb({type:db.String,optional:!0})],rI.prototype,"alg",void 0);class sI extends rI{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class iI extends rI{}class nI extends sI{get alg(){switch(this.algorithm.name.toUpperCase()){case"AES-CBC":return`A${this.algorithm.length}CBC`;case"AES-CTR":return`A${this.algorithm.length}CTR`;case"AES-GCM":return`A${this.algorithm.length}GCM`;case"AES-KW":return`A${this.algorithm.length}KW`;case"AES-CMAC":return`A${this.algorithm.length}CMAC`;case"AES-ECB":return`A${this.algorithm.length}ECB`;default:throw new xb("Unsupported algorithm name")}}set alg(e){}}nb([Cb({name:"k",converter:tI})],nI.prototype,"data",void 0);class oI{static async generateKey(e,t,r){const s=new nI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=ZA().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof nI))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return Sb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new _b("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Eb.fromJSON(t,{targetSchema:nI});break;case"raw":n=new nI,n.data=YA.Buffer.from(t);break;default:throw new _b("format: Must be 'jwk' or 'raw'")}switch(n.algorithm=r,n.algorithm.length=n.data.length<<3,n.extractable=s,n.usages=i,n.algorithm.length){case 128:case 192:case 256:break;default:throw new _b("keyData: Is wrong key length")}return n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"AES-CBC":return this.encryptAesCBC(e,t,YA.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,YA.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,YA.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,YA.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,YA.Buffer.from(r));default:throw new _b("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof nI))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,YA.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,YA.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,YA.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,YA.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,YA.Buffer.from(r));default:throw new _b("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=ZA().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=ZA().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=ZA().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,YA.Buffer.from(e.counter));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=ZA().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=ZA().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,YA.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(YA.Buffer.from(e.additionalData));let i=s.update(r);return i=YA.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=ZA().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),o=r.slice(r.length-s);e.additionalData&&i.setAAD(YA.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=YA.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=ZA().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=ZA().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=ZA().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=ZA().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}oI.AES_KW_IV=YA.Buffer.from("A6A6A6A6A6A6A6A6","hex");const aI=new WeakMap;function cI(e){const t=aI.get(e);if(!t)throw new _b("Cannot get CryptoKey from secure storage");return t}function lI(e){const t=zb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),aI.set(t,e),t}class hI extends Nb{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return oI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return oI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}const uI=YA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),dI=YA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),gI=16;function fI(e){const t=YA.Buffer.alloc(e.length),r=e.length-1;for(let s=0;s<r;s++)t[s]=e[s]<<1,128&e[s+1]&&(t[s]+=1);return t[r]=e[r]<<1,t}function pI(e,t){const r=Math.min(e.length,t.length),s=YA.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function yI(e,t){const r=ZA().createCipheriv("aes"+(e.length<<3),e,uI),s=r.update(t);return r.final(),s}function mI(e,t){const r=YA.Buffer.alloc(gI),s=t*gI,i=s+gI;return e.copy(r,0,s,i),r}class bI extends Db{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onSign(e,t,r){const s=function(e,t){const r=function(e){const t=yI(e,uI);let r=fI(t);128&t[0]&&(r=pI(r,dI));let s=fI(r);return 128&r[0]&&(s=pI(s,dI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/gI);0===n?(n=1,s=!1):s=t.length%gI===0;const o=n-1;i=s?pI(mI(t,o),r.subkey1):pI(function(e,t){const r=YA.Buffer.alloc(gI),s=t*gI,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,o),r.subkey2);let a,c=uI;for(let r=0;r<o;r++)a=pI(c,mI(t,r)),c=yI(e,a);return a=pI(i,c),yI(e,a)}(cI(t).data,YA.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===YA.Buffer.from(r).compare(YA.Buffer.from(i))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}class AI extends Mb{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return oI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return oI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}class II extends Lb{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return oI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return oI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}class vI extends Hb{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return oI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return oI.decrypt(e,cI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}class wI extends Pb{async onGenerateKey(e,t,r){return lI(await oI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return oI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return oI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return oI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await oI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof nI))throw new TypeError("key: Is not a AesCryptoKey")}}class SI extends sI{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new xb("Unsupported algorithm name")}}set alg(e){}}nb([Cb({name:"k",converter:tI})],SI.prototype,"data",void 0);class EI{static async generateKey(e,t,r){const s=new SI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=ZA().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Sb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new _b("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Eb.fromJSON(t,{targetSchema:SI});break;case"raw":n=new SI,n.data=YA.Buffer.from(t);break;default:throw new _b("format: Must be 'jwk' or 'raw'")}return n.algorithm=r,n.extractable=s,n.usages=i,n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"DES-CBC":return this.encryptDesCBC(e,t,YA.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,YA.Buffer.from(r));default:throw new _b("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof SI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,YA.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,YA.Buffer.from(r));default:throw new _b("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=ZA().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=ZA().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=ZA().createCipheriv("des-ede3-cbc",t.data,YA.Buffer.from(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=ZA().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=YA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class CI extends Kb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return lI(await EI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return EI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return EI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return EI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){const n=await EI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new _b("keyData: Wrong key size");return lI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof SI))throw new TypeError("key: Is not a DesCryptoKey")}}class kI extends Kb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return lI(await EI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return EI.encrypt(e,cI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return EI.decrypt(e,cI(t),new Uint8Array(r))}async onExportKey(e,t){return EI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){const n=await EI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new _b("keyData: Wrong key size");return lI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof SI))throw new TypeError("key: Is not a DesCryptoKey")}}function xI(e){switch(e.name.toUpperCase()){case"RSA-OAEP":{const t=/(\d+)$/.exec(e.hash.name)[1];return"RSA-OAEP"+("1"!==t?`-${t}`:"")}case"RSASSA-PKCS1-V1_5":return`RS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PSS":return`PS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PKCS1":return"RS1";default:throw new _b("algorithm: Is not recognized")}}class BI extends iI{constructor(){super(...arguments),this.type="private"}getKey(){const e=tb.parse(this.data,MA.PrivateKeyInfo);return tb.parse(e.privateKey,MA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:xI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Sb.toJSON(e))}fromJSON(e){const t=Eb.fromJSON(e,{targetSchema:MA.RsaPrivateKey}),r=new MA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=rb.serialize(t),this.data=YA.Buffer.from(rb.serialize(r))}}class _I extends iI{constructor(){super(...arguments),this.type="public"}getKey(){const e=tb.parse(this.data,MA.PublicKeyInfo);return tb.parse(e.publicKey,MA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:xI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Sb.toJSON(e))}fromJSON(e){const t=Eb.fromJSON(e,{targetSchema:MA.RsaPublicKey}),r=new MA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=rb.serialize(t),this.data=YA.Buffer.from(rb.serialize(r))}}class RI{static async generateKey(e,t,r){const s=new BI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new _I;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=YA.Buffer.concat([YA.Buffer.alloc(4-e.publicExponent.byteLength,0),YA.Buffer.from(e.publicExponent)]).readInt32BE(0),o=ZA().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Sb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new _b("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=Eb.fromJSON(t,{targetSchema:MA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Eb.fromJSON(t,{targetSchema:MA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=tb.parse(new Uint8Array(t),MA.PublicKeyInfo),n=tb.parse(e.publicKey,MA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=tb.parse(new Uint8Array(t),MA.PrivateKeyInfo),n=tb.parse(e.privateKey,MA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new _b("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async sign(e,t,r){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.signRsa(e,t,r);default:throw new _b("algorithm: Is not recognized")}}static async verify(e,t,r,s){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.verifySSA(e,t,s,r);default:throw new _b("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new _b("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new _b("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new MA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=rb.serialize(e);const n=new BI;return n.data=YA.Buffer.from(rb.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static importPublicKey(e,t,r,s){const i=new MA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=rb.serialize(e);const n=new _I;return n.data=YA.Buffer.from(rb.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static getCryptoAlgorithm(e){switch(e.hash.name.toUpperCase()){case"SHA-1":return"RSA-SHA1";case"SHA-256":return"RSA-SHA256";case"SHA-384":return"RSA-SHA384";case"SHA-512":return"RSA-SHA512";case"SHA3-256":return"RSA-SHA3-256";case"SHA3-384":return"RSA-SHA3-384";case"SHA3-512":return"RSA-SHA3-512";default:throw new _b("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=ZA().createSign(s);i.update(YA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem};"RSA-PSS"===e.name.toUpperCase()&&(n.padding=ZA().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const o=i.sign(n);return new Uint8Array(o).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=ZA().createVerify(i);n.update(YA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(o.padding=ZA().constants.RSA_PKCS1_PSS_PADDING,o.saltLength=e.saltLength),n.verify(o,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:ZA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(ZA().publicEncrypt(s,r)).buffer}static decryptOAEP(e,t,r){const s={key:`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`,padding:ZA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(ZA().privateDecrypt(s,r)).buffer}}RI.publicKeyUsages=["verify","encrypt","wrapKey"],RI.privateKeyUsages=["sign","decrypt","unwrapKey"];class OI extends Qb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await RI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onSign(e,t,r){return RI.sign(e,cI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return RI.verify(e,cI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return RI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await RI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof BI||r instanceof _I))throw new TypeError("key: Is not RSA CryptoKey")}}class UI extends Fb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await RI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onSign(e,t,r){return RI.sign(e,cI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return RI.verify(e,cI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return RI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await RI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof BI||r instanceof _I))throw new TypeError("key: Is not RSA CryptoKey")}}class TI{static size(e){switch(e.name.toUpperCase()){case"SHA-1":return 160;case"SHA-256":case"SHA3-256":return 256;case"SHA-384":case"SHA3-384":return 384;case"SHA-512":case"SHA3-512":return 512;default:throw new Error("Unrecognized name")}}static getAlgorithmName(e){switch(e.name.toUpperCase()){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512";case"SHA3-256":return"sha3-256";case"SHA3-384":return"sha3-384";case"SHA3-512":return"sha3-512";default:throw new Error("Unrecognized name")}}static digest(e,t){const r=this.getAlgorithmName(e),s=ZA().createHash(r).update(YA.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class NI extends Gb{async onGenerateKey(e,t,r){const s=await RI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onEncrypt(e,t,r){const s=cI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=TI.size(s.algorithm.hash)>>3,a=i.byteLength,c=n-a-2*o-2;if(a>n-2*o-2)throw new Error("Data too large");const l=new Uint8Array(n),h=l.subarray(1,o+1),u=l.subarray(o+1);u.set(i,o+c+1);const d=ZA().createHash(s.algorithm.hash.name.replace("-","")).update(Hf.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,ZA().randomFillSync(h);const g=this.mgf1(s.algorithm.hash,h,u.length);for(let e=0;e<u.length;e++)u[e]^=g[e];const f=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=f[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=ZA().publicEncrypt({key:s.pem,padding:ZA().constants.RSA_NO_PADDING},YA.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=cI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=TI.size(s.algorithm.hash)>>3;if(r.byteLength!==i)throw new Error("Bad data");s.pem||(s.pem=`-----BEGIN PRIVATE KEY-----\n${s.data.toString("base64")}\n-----END PRIVATE KEY-----`);let o=ZA().privateDecrypt({key:s.pem,padding:ZA().constants.RSA_NO_PADDING},YA.Buffer.from(r));const a=o[0],c=o.subarray(1,n+1),l=o.subarray(n+1);if(0!==a)throw new Error("Decryption failed");const h=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=h[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const d=ZA().createHash(s.algorithm.hash.name.replace("-","")).update(Hf.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(d[e]!==l[e])throw new Error("Decryption failed");let g=n;for(;g<l.length;g++){const e=l[g];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(g===l.length)throw new Error("Decryption failed");return o=l.subarray(g+1),new Uint8Array(o).buffer}async onExportKey(e,t){return RI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await RI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof BI||r instanceof _I))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=TI.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),o=Math.ceil(r/s);for(let r=0;r<o;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const o=i.subarray(r*s);let a=ZA().createHash(e.name.replace("-","")).update(t).update(n).digest();a.length>o.length&&(a=a.subarray(0,o.length)),o.set(a)}return i}}class DI extends Ub{constructor(){super(...arguments),this.name="RSAES-PKCS1-v1_5",this.usages={publicKey:["encrypt","wrapKey"],privateKey:["decrypt","unwrapKey"]}}async onGenerateKey(e,t,r){const s=await RI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=jf.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");switch(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength){case 1024:case 2048:case 4096:break;default:throw new TypeError("modulusLength: Must be 1024, 2048, or 4096")}}async onEncrypt(e,t,r){const s=this.toCryptoOptions(t),i=ZA().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=ZA().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return RI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await RI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof BI||r instanceof _I))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${cI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:ZA().constants.RSA_PKCS1_PADDING}}}const MI={"1.2.840.10045.3.1.7":"P-256","P-256":"1.2.840.10045.3.1.7","1.3.132.0.34":"P-384","P-384":"1.3.132.0.34","1.3.132.0.35":"P-521","P-521":"1.3.132.0.35","1.3.132.0.10":"K-256","K-256":"1.3.132.0.10",brainpoolP160r1:"1.3.36.3.3.2.8.1.1.1","1.3.36.3.3.2.8.1.1.1":"brainpoolP160r1",brainpoolP160t1:"1.3.36.3.3.2.8.1.1.2","1.3.36.3.3.2.8.1.1.2":"brainpoolP160t1",brainpoolP192r1:"1.3.36.3.3.2.8.1.1.3","1.3.36.3.3.2.8.1.1.3":"brainpoolP192r1",brainpoolP192t1:"1.3.36.3.3.2.8.1.1.4","1.3.36.3.3.2.8.1.1.4":"brainpoolP192t1",brainpoolP224r1:"1.3.36.3.3.2.8.1.1.5","1.3.36.3.3.2.8.1.1.5":"brainpoolP224r1",brainpoolP224t1:"1.3.36.3.3.2.8.1.1.6","1.3.36.3.3.2.8.1.1.6":"brainpoolP224t1",brainpoolP256r1:"1.3.36.3.3.2.8.1.1.7","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1",brainpoolP256t1:"1.3.36.3.3.2.8.1.1.8","1.3.36.3.3.2.8.1.1.8":"brainpoolP256t1",brainpoolP320r1:"1.3.36.3.3.2.8.1.1.9","1.3.36.3.3.2.8.1.1.9":"brainpoolP320r1",brainpoolP320t1:"1.3.36.3.3.2.8.1.1.10","1.3.36.3.3.2.8.1.1.10":"brainpoolP320t1",brainpoolP384r1:"1.3.36.3.3.2.8.1.1.11","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1",brainpoolP384t1:"1.3.36.3.3.2.8.1.1.12","1.3.36.3.3.2.8.1.1.12":"brainpoolP384t1",brainpoolP512r1:"1.3.36.3.3.2.8.1.1.13","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1",brainpoolP512t1:"1.3.36.3.3.2.8.1.1.14","1.3.36.3.3.2.8.1.1.14":"brainpoolP512t1"};function PI(e){const t=MI[e];if(!t)throw new _b(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class LI extends iI{constructor(){super(...arguments),this.type="private"}getKey(){const e=tb.parse(this.data,MA.PrivateKeyInfo);return tb.parse(e.privateKey,MA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Sb.toJSON(e))}fromJSON(e){if(!e.crv)throw new _b("Cannot get named curve from JWK. Property 'crv' is required");const t=new MA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=rb.serialize(new MA.ObjectIdentifier(PI(e.crv)));const r=Eb.fromJSON(e,{targetSchema:MA.EcPrivateKey});return t.privateKey=rb.serialize(r),this.data=YA.Buffer.from(rb.serialize(t)),this}}class HI extends iI{constructor(){super(...arguments),this.type="public"}getKey(){const e=tb.parse(this.data,MA.PublicKeyInfo);return new MA.EcPublicKey(e.publicKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Sb.toJSON(e))}fromJSON(e){if(!e.crv)throw new _b("Cannot get named curve from JWK. Property 'crv' is required");const t=Eb.fromJSON(e,{targetSchema:MA.EcPublicKey}),r=new MA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=rb.serialize(new MA.ObjectIdentifier(PI(e.crv))),r.publicKey=rb.toASN(t).valueHex,this.data=YA.Buffer.from(rb.serialize(r)),this}}class KI extends Ub{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class VI extends Ub{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class QI extends Ub{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class FI extends Ub{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class GI extends Ub{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class $I extends Ub{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class jI extends Ub{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return TI.digest(e,t)}}class qI{static async generateKey(e,t,r){const s=new LI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new HI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=ZA().generateKeyPairSync("ec",{namedCurve:this.getOpenSSLNamedCurve(e.namedCurve),publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=n.privateKey,i.data=n.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){const s=TI.getAlgorithmName(e.hash),i=ZA().createSign(s);i.update(YA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},o=i.sign(n),a=tb.parse(o,MA.EcDsaSignature);return hA.encodeSignature(a,PA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=TI.getAlgorithmName(e.hash),n=ZA().createVerify(i);n.update(YA.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem},a=new MA.EcDsaSignature,c=PA.get(t.algorithm.namedCurve),l=hA.decodeSignature(r,c.size);a.r=Hf.toArrayBuffer(l.r),a.s=Hf.toArrayBuffer(l.s);const h=YA.Buffer.from(rb.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=ZA().createECDH(s),n=tb.parse(t.data,MA.PrivateKeyInfo),o=tb.parse(n.privateKey,MA.EcPrivateKey);i.setPrivateKey(YA.Buffer.from(o.privateKey));const a=tb.parse(e.public.data,MA.PublicKeyInfo),c=i.computeSecret(YA.Buffer.from(a.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Sb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return tb.parse(t.data,MA.PublicKeyInfo).publicKey;default:throw new _b("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=Eb.fromJSON(t,{targetSchema:MA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Eb.fromJSON(t,{targetSchema:MA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new MA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=tb.parse(new Uint8Array(t),MA.PublicKeyInfo),n=new MA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=tb.parse(new Uint8Array(t),MA.PrivateKeyInfo),n=tb.parse(e.privateKey,MA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new _b("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new kb("Key info doesn't have required parameters");let r="";try{r=tb.parse(e,MA.ObjectIdentifier).value}catch(e){throw new kb("Cannot read key info parameters")}if(PI(t)!==r)throw new kb("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new MA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=rb.serialize(new MA.ObjectIdentifier(PI(t.namedCurve))),i.privateKey=rb.serialize(e);const n=new LI;return n.data=YA.Buffer.from(rb.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new MA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=PI(t.namedCurve);i.publicKeyAlgorithm.parameters=rb.serialize(new MA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new HI;return o.data=YA.Buffer.from(rb.serialize(i)),o.algorithm=Object.assign({},t),o.extractable=r,o.usages=s,o}static getOpenSSLNamedCurve(e){switch(e.toUpperCase()){case"P-256":return"prime256v1";case"K-256":return"secp256k1";case"P-384":return"secp384r1";case"P-521":return"secp521r1";default:return e}}}qI.publicKeyUsages=["verify"],qI.privateKeyUsages=["sign","deriveKey","deriveBits"];class zI extends jb{constructor(){super(...arguments),this.namedCurves=PA.names,this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await qI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onSign(e,t,r){return qI.sign(e,cI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return qI.verify(e,cI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return qI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await qI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof LI||r instanceof HI))throw new TypeError("key: Is not EC CryptoKey")}}class WI extends Wb{constructor(){super(...arguments),this.namedCurves=PA.names}async onGenerateKey(e,t,r){const s=await qI.generateKey({...e,name:this.name},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onExportKey(e,t){return qI.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await qI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=cI(e);if(!(r instanceof LI||r instanceof HI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await qI.deriveBits({...e,public:cI(e.public)},cI(t),r)}}const JI={[MA.idEd448]:"Ed448",ed448:MA.idEd448,[MA.idX448]:"X448",x448:MA.idX448,[MA.idEd25519]:"Ed25519",ed25519:MA.idEd25519,[MA.idX25519]:"X25519",x25519:MA.idX25519};function YI(e){const t=JI[e.toLowerCase()];if(!t)throw new _b(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class XI extends iI{constructor(){super(...arguments),this.type="private"}getKey(){const e=tb.parse(this.data,MA.PrivateKeyInfo);return tb.parse(e.privateKey,MA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Sb.toJSON(e))}fromJSON(e){if(!e.crv)throw new _b("Cannot get named curve from JWK. Property 'crv' is required");const t=new MA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=YI(e.crv);const r=Eb.fromJSON(e,{targetSchema:MA.CurvePrivateKey});return t.privateKey=rb.serialize(r),this.data=YA.Buffer.from(rb.serialize(t)),this}}class ZI extends iI{constructor(){super(...arguments),this.type="public"}getKey(){return tb.parse(this.data,MA.PublicKeyInfo).publicKey}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,{x:jf.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new _b("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new _b("Cannot get property from JWK. Property 'x' is required");const t=new MA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=YI(e.crv),t.publicKey=jf.FromBase64Url(e.x),this.data=YA.Buffer.from(rb.serialize(t)),this}}class ev{static async generateKey(e,t,r){const s=new XI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new ZI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=ZA().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const s={key:t.pem},i=ZA().sign(null,YA.Buffer.from(r),s);return Hf.toArrayBuffer(i)}static async verify(e,t,r,s){t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const i={key:t.pem};return ZA().verify(null,YA.Buffer.from(s),i,YA.Buffer.from(r))}static async deriveBits(e,t,r){const s=ZA().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=ZA().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=ZA().diffieHellman({publicKey:s,privateKey:i});return new Uint8Array(n).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Sb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return tb.parse(t.data,MA.PublicKeyInfo).publicKey;default:throw new _b("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":{const e=t;if(e.d){const e=Eb.fromJSON(t,{targetSchema:MA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(jf.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=tb.parse(new Uint8Array(t),MA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=tb.parse(new Uint8Array(t),MA.PrivateKeyInfo),n=tb.parse(e.privateKey,MA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new _b("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new XI;return i.fromJSON({crv:t.namedCurve,d:jf.ToBase64Url(e.d)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}static async importPublicKey(e,t,r,s){const i=new ZI;return i.fromJSON({crv:t.namedCurve,x:jf.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}ev.publicKeyUsages=["verify"],ev.privateKeyUsages=["sign","deriveKey","deriveBits"];class tv extends Yb{async onGenerateKey(e,t,r){const s=await ev.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onSign(e,t,r){return ev.sign(e,cI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return ev.verify(e,cI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return ev.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await ev.importKey(e,t,{...r,name:this.name},s,i))}}class rv extends Jb{async onGenerateKey(e,t,r){const s=await ev.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onDeriveBits(e,t,r){return await ev.deriveBits({...e,public:cI(e.public)},cI(t),r)}async onExportKey(e,t){return ev.exportKey(e,cI(t))}async onImportKey(e,t,r,s,i){return lI(await ev.importKey(e,t,{...r,name:this.name},s,i))}}class sv extends rI{constructor(e,t,r,s){super(),this.algorithm=e,this.extractable=t,this.usages=r,this.data=Buffer.from(s)}toJWK(){return{kty:"OKP",crv:this.algorithm.name,key_ops:this.usages,ext:this.extractable}}}class iv extends sv{constructor(){super(...arguments),this.type="private"}toJWK(){const e=ZA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Ob.toUint8Array(this.data.toString()),r=ib.parse(t,MA.PrivateKeyInfo),s=ib.parse(r.privateKey,MA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class nv extends sv{constructor(){super(...arguments),this.type="public"}toJWK(){const e=ZA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class ov{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=ZA().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},o=r.filter(e=>this.privateKeyUsages.includes(e)),a=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new iv(n,t,o,i.privateKey),publicKey:new nv(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=ZA().sign(null,Buffer.from(r),t.data);return Hf.toArrayBuffer(s)}static async verify(e,t,r,s){return ZA().verify(null,Buffer.from(s),t.data,r)}static async exportKey(e,t){switch(e){case"jwk":return t.toJWK();case"pkcs8":case"spki":return Ob.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return jf.FromBase64Url(e.x)}default:return Promise.reject(new _b("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}static async importKey(e,t,r,s,i){switch(e){case"jwk":{const e=t;if(e.d){const t=new MA.EdPrivateKey;t.value=Hf.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new MA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?MA.idEd25519:MA.idX25519,n.privateKey=ib.serialize(t);const o=ib.serialize(n),a=Ob.fromBufferSource(o,"PRIVATE KEY");return new iv(r,s,i,a)}if(e.x){const t=ZA().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new nv(r,s,i,t)}throw new _b("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Ob.fromBufferSource(t,"PRIVATE KEY");return new iv(r,s,i,e)}case"spki":{const e=Ob.fromBufferSource(t,"PUBLIC KEY");return new nv(r,s,i,e)}case"raw":{const e=t,n=ZA().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:jf.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new nv(r,s,i,n)}default:return Promise.reject(new _b("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}ov.privateKeyUsages=["sign","deriveBits","deriveKey"],ov.publicKeyUsages=["verify"];class av extends HA{async onGenerateKey(e,t,r){const s=await ov.generateKey(e,t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onSign(e,t,r){const s=cI(t);return ov.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=cI(t);return ov.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=cI(t);return ov.exportKey(e,r)}async onImportKey(e,t,r,s,i){return lI(await ov.importKey(e,t,r,s,i))}}class cv extends LA{async onGenerateKey(e,t,r){const s=await ov.generateKey(e,t,r);return{privateKey:lI(s.privateKey),publicKey:lI(s.publicKey)}}async onDeriveBits(e,t,r){const s=cI(t),i=cI(e.public),n=ZA().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=ZA().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=ZA().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=cI(t);return ov.exportKey(e,r)}async onImportKey(e,t,r,s,i){return lI(await ov.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof sv))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class lv extends rI{}class hv extends VA{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=Hf.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");ZA().pbkdf2(cI(t).data,YA.Buffer.from(n),e.iterations,r>>3,o,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new lv;return e.data=YA.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,lI(e)}throw new _b("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof lv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class uv extends rI{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}nb([Cb({name:"k",converter:tI})],uv.prototype,"data",void 0);class dv extends KA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new uv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=ZA().randomBytes(s>>3),lI(i)}async onSign(e,t,r){const s=TI.getAlgorithmName(t.algorithm.hash),i=ZA().createHmac(s,cI(t).data).update(YA.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=TI.getAlgorithmName(t.algorithm.hash);return 0===ZA().createHmac(i,cI(t).data).update(YA.Buffer.from(s)).digest().compare(YA.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Eb.fromJSON(t,{targetSchema:uv});break;case"raw":n=new uv,n.data=YA.Buffer.from(t);break;default:throw new _b("format: Must be 'jwk' or 'raw'")}return n.algorithm={hash:{name:r.hash.name},name:this.name,length:n.data.length<<3},n.extractable=s,n.usages=i,lI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return Sb.toJSON(cI(t));case"raw":return new Uint8Array(cI(t).data).buffer;default:throw new _b("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof uv))throw new TypeError("key: Is not HMAC CryptoKey")}}class gv extends rI{}class fv extends QA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new _b("Operation not supported");const n=new gv;return n.data=YA.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,lI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=ZA().createHash(s).digest().length,n=r/8,o=Hf.toUint8Array(e.info),a=ZA().createHmac(s,Hf.toUint8Array(e.salt)).update(Hf.toUint8Array(cI(t).data)).digest(),c=[YA.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(ZA().createHmac(s,a).update(YA.Buffer.concat([c[e-1],o,YA.Buffer.from([e])])).digest());return YA.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(cI(e)instanceof gv))throw new TypeError("key: Is not HKDF CryptoKey")}}class pv{static digest(e,t){const r=ZA().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(YA.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class yv extends GA{async onDigest(e,t){return pv.digest(e,t)}}class mv extends $A{async onDigest(e,t){return pv.digest(e,t)}}class bv extends JA{constructor(){var e;super(),this.providers.set(new hI),this.providers.set(new AI),this.providers.set(new II),this.providers.set(new bI),this.providers.set(new vI),this.providers.set(new wI),ZA().getCiphers().includes("des-cbc")&&this.providers.set(new CI),this.providers.set(new kI),this.providers.set(new OI),this.providers.set(new UI),this.providers.set(new NI),this.providers.set(new DI),this.providers.set(new zI),this.providers.set(new WI),this.providers.set(new KI),this.providers.set(new VI),this.providers.set(new QI),this.providers.set(new FI),this.providers.set(new hv),this.providers.set(new dv),this.providers.set(new fv);const t=null===(e=/^v(\d+)/.exec(eI.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new yv),this.providers.set(new mv));const r=ZA().getHashes();r.includes("sha3-256")&&this.providers.set(new GI),r.includes("sha3-384")&&this.providers.set(new $I),r.includes("sha3-512")&&this.providers.set(new jI),t&&parseInt(t,10)>=14&&(this.providers.set(new tv),this.providers.set(new rv),this.providers.set(new av),this.providers.set(new cv))}}var Av,Iv,vv;o(909);class wv{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map(e=>{const t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t})}static parseIPv6(e){const t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce((e,t)=>{const r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e},[])}static expandIPv6(e){if(!e.includes("::"))return e;const t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");const r=t[0]?t[0].split(":"):[],s=t[1]?t[1].split(":"):[],i=8-(r.length+s.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...s].join(":")}static formatIPv6(e){const t=[];for(let r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){const t=e.split(":");let r=-1,s=0,i=-1,n=0;for(let e=0;e<t.length;e++)"0"===t[e]?(-1===i&&(i=e),n++):(n>s&&(r=i,s=n),i=-1,n=0);return n>s&&(r=i,s=n),s>1?`${t.slice(0,r).join(":")}::${t.slice(r+s).join(":")}`:e}static parseCIDR(e){const[t,r]=e.split("/"),s=parseInt(r,10);if(this.isIPv4(t)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),s]}if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),s]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;const t=parseInt(e.slice(8),16).toString(2).split("").reduce((e,t)=>e+ +t,0);let r=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return r=r.slice(0,-1),`${r}/${t}`}static toString(e){const t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){const e=t.length/2,r=t.slice(0,e),s=t.slice(e);if(t.every(e=>0===e))return 8===t.length?"0.0.0.0/0":"::/0";const i=s.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return 8===t.length?`${Array.from(r).join(".")}/${i}`:`${this.formatIPv6(r)}/${i}`}return this.decodeIP(jf.ToHex(e))}static fromString(e){if(e.includes("/")){const[t,r]=this.parseCIDR(e),s=new Uint8Array(t.length);let i=r;for(let e=0;e<s.length;e++)i>=8?(s[e]=255,i-=8):i>0&&(s[e]=255<<8-i,i=0);const n=new Uint8Array(2*t.length);return n.set(t,0),n.set(s,t.length),n.buffer}const t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}let Sv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};nb([Zm({type:dy.TeletexString})],Sv.prototype,"teletexString",void 0),nb([Zm({type:dy.PrintableString})],Sv.prototype,"printableString",void 0),nb([Zm({type:dy.UniversalString})],Sv.prototype,"universalString",void 0),nb([Zm({type:dy.Utf8String})],Sv.prototype,"utf8String",void 0),nb([Zm({type:dy.BmpString})],Sv.prototype,"bmpString",void 0),Sv=nb([Xm({type:uy.Choice})],Sv);let Ev=class extends Sv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?jf.ToHex(this.anyValue):super.toString())}};nb([Zm({type:dy.IA5String})],Ev.prototype,"ia5String",void 0),nb([Zm({type:dy.Any})],Ev.prototype,"anyValue",void 0),Ev=nb([Xm({type:uy.Choice})],Ev);class Cv{constructor(e={}){this.type="",this.value=new Ev,Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Cv.prototype,"type",void 0),nb([Zm({type:Ev})],Cv.prototype,"value",void 0);let kv=Av=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Av.prototype)}};kv=Av=nb([Xm({type:uy.Set,itemType:Cv})],kv);let xv=Iv=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Iv.prototype)}};xv=Iv=nb([Xm({type:uy.Sequence,itemType:kv})],xv);let Bv=vv=class extends xv{constructor(e){super(e),Object.setPrototypeOf(this,vv.prototype)}};Bv=vv=nb([Xm({type:uy.Sequence})],Bv);const _v={fromASN:e=>wv.toString(_m.fromASN(e)),toASN:e=>_m.toASN(wv.fromString(e))};class Rv{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Rv.prototype,"typeId",void 0),nb([Zm({type:dy.Any,context:0})],Rv.prototype,"value",void 0);class Ov{constructor(e={}){this.partyName=new Sv,Object.assign(this,e)}}nb([Zm({type:Sv,optional:!0,context:0,implicit:!0})],Ov.prototype,"nameAssigner",void 0),nb([Zm({type:Sv,context:1,implicit:!0})],Ov.prototype,"partyName",void 0);let Uv=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:Rv,context:0,implicit:!0})],Uv.prototype,"otherName",void 0),nb([Zm({type:dy.IA5String,context:1,implicit:!0})],Uv.prototype,"rfc822Name",void 0),nb([Zm({type:dy.IA5String,context:2,implicit:!0})],Uv.prototype,"dNSName",void 0),nb([Zm({type:dy.Any,context:3,implicit:!0})],Uv.prototype,"x400Address",void 0),nb([Zm({type:Bv,context:4,implicit:!1})],Uv.prototype,"directoryName",void 0),nb([Zm({type:Ov,context:5})],Uv.prototype,"ediPartyName",void 0),nb([Zm({type:dy.IA5String,context:6,implicit:!0})],Uv.prototype,"uniformResourceIdentifier",void 0),nb([Zm({type:dy.OctetString,context:7,implicit:!0,converter:_v})],Uv.prototype,"iPAddress",void 0),nb([Zm({type:dy.ObjectIdentifier,context:8,implicit:!0})],Uv.prototype,"registeredID",void 0),Uv=nb([Xm({type:uy.Choice})],Uv);const Tv="1.3.6.1.5.5.7",Nv=`${Tv}.3`,Dv=`${Tv}.48`,Mv=`${Dv}.1`,Pv=`${Dv}.2`,Lv=`${Dv}.3`,Hv=`${Dv}.5`,Kv="2.5.29";var Vv;const Qv=`${Tv}.1.1`;class Fv{constructor(e={}){this.accessMethod="",this.accessLocation=new Uv,Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Fv.prototype,"accessMethod",void 0),nb([Zm({type:Uv})],Fv.prototype,"accessLocation",void 0);let Gv=Vv=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Vv.prototype)}};Gv=Vv=nb([Xm({type:uy.Sequence,itemType:Fv})],Gv);const $v=`${Kv}.35`;class jv extends vm{}class qv{constructor(e={}){e&&Object.assign(this,e)}}nb([Zm({type:jv,context:0,optional:!0,implicit:!0})],qv.prototype,"keyIdentifier",void 0),nb([Zm({type:Uv,context:1,optional:!0,implicit:!0,repeated:"sequence"})],qv.prototype,"authorityCertIssuer",void 0),nb([Zm({type:dy.Integer,context:2,optional:!0,implicit:!0,converter:Cm})],qv.prototype,"authorityCertSerialNumber",void 0);const zv=`${Kv}.19`;class Wv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Jv;nb([Zm({type:dy.Boolean,defaultValue:!1})],Wv.prototype,"cA",void 0),nb([Zm({type:dy.Integer,optional:!0})],Wv.prototype,"pathLenConstraint",void 0);let Yv=Jv=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Jv.prototype)}};var Xv;Yv=Jv=nb([Xm({type:uy.Sequence,itemType:Uv})],Yv);let Zv=Xv=class extends Yv{constructor(e){super(e),Object.setPrototypeOf(this,Xv.prototype)}};var ew;Zv=Xv=nb([Xm({type:uy.Sequence})],Zv);const tw=`${Kv}.32`;let rw=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};nb([Zm({type:dy.IA5String})],rw.prototype,"ia5String",void 0),nb([Zm({type:dy.VisibleString})],rw.prototype,"visibleString",void 0),nb([Zm({type:dy.BmpString})],rw.prototype,"bmpString",void 0),nb([Zm({type:dy.Utf8String})],rw.prototype,"utf8String",void 0),rw=nb([Xm({type:uy.Choice})],rw);class sw{constructor(e={}){this.organization=new rw,this.noticeNumbers=[],Object.assign(this,e)}}nb([Zm({type:rw})],sw.prototype,"organization",void 0),nb([Zm({type:dy.Integer,repeated:"sequence"})],sw.prototype,"noticeNumbers",void 0);class iw{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:sw,optional:!0})],iw.prototype,"noticeRef",void 0),nb([Zm({type:rw,optional:!0})],iw.prototype,"explicitText",void 0);let nw=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:dy.IA5String})],nw.prototype,"cPSuri",void 0),nb([Zm({type:iw})],nw.prototype,"userNotice",void 0),nw=nb([Xm({type:uy.Choice})],nw);class ow{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],ow.prototype,"policyQualifierId",void 0),nb([Zm({type:dy.Any})],ow.prototype,"qualifier",void 0);class aw{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],aw.prototype,"policyIdentifier",void 0),nb([Zm({type:ow,repeated:"sequence",optional:!0})],aw.prototype,"policyQualifiers",void 0);let cw=ew=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,ew.prototype)}};cw=ew=nb([Xm({type:uy.Sequence,itemType:aw})],cw);let lw=class{constructor(e=0){this.value=e}};nb([Zm({type:dy.Integer})],lw.prototype,"value",void 0),lw=nb([Xm({type:uy.Choice})],lw);let hw=class extends lw{};var uw;hw=nb([Xm({type:uy.Choice})],hw);const dw=`${Kv}.31`;var gw;!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(gw||(gw={}));class fw extends Im{toJSON(){const e=[],t=this.toNumber();return t&gw.aACompromise&&e.push("aACompromise"),t&gw.affiliationChanged&&e.push("affiliationChanged"),t&gw.cACompromise&&e.push("cACompromise"),t&gw.certificateHold&&e.push("certificateHold"),t&gw.cessationOfOperation&&e.push("cessationOfOperation"),t&gw.keyCompromise&&e.push("keyCompromise"),t&gw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&gw.superseded&&e.push("superseded"),t&gw.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let pw=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:Uv,context:0,repeated:"sequence",implicit:!0})],pw.prototype,"fullName",void 0),nb([Zm({type:kv,context:1,implicit:!0})],pw.prototype,"nameRelativeToCRLIssuer",void 0),pw=nb([Xm({type:uy.Choice})],pw);class yw{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:pw,context:0,optional:!0})],yw.prototype,"distributionPoint",void 0),nb([Zm({type:fw,context:1,optional:!0,implicit:!0})],yw.prototype,"reasons",void 0),nb([Zm({type:Uv,context:2,optional:!0,repeated:"sequence",implicit:!0})],yw.prototype,"cRLIssuer",void 0);let mw=uw=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,uw.prototype)}};var bw;mw=uw=nb([Xm({type:uy.Sequence,itemType:yw})],mw);let Aw=bw=class extends mw{constructor(e){super(e),Object.setPrototypeOf(this,bw.prototype)}};Aw=bw=nb([Xm({type:uy.Sequence,itemType:yw})],Aw);class Iw{constructor(e={}){this.onlyContainsUserCerts=Iw.ONLY,this.onlyContainsCACerts=Iw.ONLY,this.indirectCRL=Iw.ONLY,this.onlyContainsAttributeCerts=Iw.ONLY,Object.assign(this,e)}}var vw;Iw.ONLY=!1,nb([Zm({type:pw,context:0,optional:!0})],Iw.prototype,"distributionPoint",void 0),nb([Zm({type:dy.Boolean,context:1,defaultValue:Iw.ONLY,implicit:!0})],Iw.prototype,"onlyContainsUserCerts",void 0),nb([Zm({type:dy.Boolean,context:2,defaultValue:Iw.ONLY,implicit:!0})],Iw.prototype,"onlyContainsCACerts",void 0),nb([Zm({type:fw,context:3,optional:!0,implicit:!0})],Iw.prototype,"onlySomeReasons",void 0),nb([Zm({type:dy.Boolean,context:4,defaultValue:Iw.ONLY,implicit:!0})],Iw.prototype,"indirectCRL",void 0),nb([Zm({type:dy.Boolean,context:5,defaultValue:Iw.ONLY,implicit:!0})],Iw.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(vw||(vw={}));let ww=class{constructor(e=vw.unspecified){this.reason=vw.unspecified,this.reason=e}toJSON(){return vw[this.reason]}toString(){return this.toJSON()}};var Sw;nb([Zm({type:dy.Enumerated})],ww.prototype,"reason",void 0),ww=nb([Xm({type:uy.Choice})],ww);const Ew=`${Kv}.37`;let Cw=Sw=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Sw.prototype)}};Cw=Sw=nb([Xm({type:uy.Sequence,itemType:dy.ObjectIdentifier})],Cw);const kw=`${Nv}.1`,xw=`${Nv}.2`,Bw=`${Nv}.3`,_w=`${Nv}.4`,Rw=`${Nv}.8`,Ow=`${Nv}.9`;let Uw=class{constructor(e=new ArrayBuffer(0)){this.value=e}};nb([Zm({type:dy.Integer,converter:Cm})],Uw.prototype,"value",void 0),Uw=nb([Xm({type:uy.Choice})],Uw);let Tw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var Nw;nb([Zm({type:dy.GeneralizedTime})],Tw.prototype,"value",void 0),Tw=nb([Xm({type:uy.Choice})],Tw);let Dw=Nw=class extends Yv{constructor(e){super(e),Object.setPrototypeOf(this,Nw.prototype)}};Dw=Nw=nb([Xm({type:uy.Sequence})],Dw);const Mw=`${Kv}.15`;var Pw,Lw;!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Pw||(Pw={}));class Hw extends Im{toJSON(){const e=this.toNumber(),t=[];return e&Pw.cRLSign&&t.push("crlSign"),e&Pw.dataEncipherment&&t.push("dataEncipherment"),e&Pw.decipherOnly&&t.push("decipherOnly"),e&Pw.digitalSignature&&t.push("digitalSignature"),e&Pw.encipherOnly&&t.push("encipherOnly"),e&Pw.keyAgreement&&t.push("keyAgreement"),e&Pw.keyCertSign&&t.push("keyCertSign"),e&Pw.keyEncipherment&&t.push("keyEncipherment"),e&Pw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class Kw{constructor(e={}){this.base=new Uv,this.minimum=0,Object.assign(this,e)}}nb([Zm({type:Uv})],Kw.prototype,"base",void 0),nb([Zm({type:dy.Integer,context:0,defaultValue:0,implicit:!0})],Kw.prototype,"minimum",void 0),nb([Zm({type:dy.Integer,context:1,optional:!0,implicit:!0})],Kw.prototype,"maximum",void 0);let Vw=Lw=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Lw.prototype)}};Vw=Lw=nb([Xm({type:uy.Sequence,itemType:Kw})],Vw);class Qw{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:Vw,context:0,optional:!0,implicit:!0})],Qw.prototype,"permittedSubtrees",void 0),nb([Zm({type:Vw,context:1,optional:!0,implicit:!0})],Qw.prototype,"excludedSubtrees",void 0);class Fw{constructor(e={}){Object.assign(this,e)}}var Gw;nb([Zm({type:dy.Integer,context:0,implicit:!0,optional:!0,converter:Cm})],Fw.prototype,"requireExplicitPolicy",void 0),nb([Zm({type:dy.Integer,context:1,implicit:!0,optional:!0,converter:Cm})],Fw.prototype,"inhibitPolicyMapping",void 0);class $w{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],$w.prototype,"issuerDomainPolicy",void 0),nb([Zm({type:dy.ObjectIdentifier})],$w.prototype,"subjectDomainPolicy",void 0);let jw=Gw=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Gw.prototype)}};var qw;jw=Gw=nb([Xm({type:uy.Sequence,itemType:$w})],jw);const zw=`${Kv}.17`;let Ww=qw=class extends Yv{constructor(e){super(e),Object.setPrototypeOf(this,qw.prototype)}};Ww=qw=nb([Xm({type:uy.Sequence})],Ww);class Jw{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Yw;nb([Zm({type:dy.ObjectIdentifier})],Jw.prototype,"type",void 0),nb([Zm({type:dy.Any,repeated:"set"})],Jw.prototype,"values",void 0);let Xw=Yw=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Yw.prototype)}};Xw=Yw=nb([Xm({type:uy.Sequence,itemType:Jw})],Xw);const Zw=`${Kv}.14`;class eS extends jv{}class tS{constructor(e={}){Object.assign(this,e)}}var rS,sS;nb([Zm({type:dy.GeneralizedTime,context:0,implicit:!0,optional:!0})],tS.prototype,"notBefore",void 0),nb([Zm({type:dy.GeneralizedTime,context:1,implicit:!0,optional:!0})],tS.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(rS||(rS={}));class iS extends Im{toJSON(){const e=[],t=this.toNumber();return t&rS.pKIXCertificate&&e.push("pKIXCertificate"),t&rS.newExtensions&&e.push("newExtensions"),t&rS.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class nS{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new iS,Object.assign(this,e)}}nb([Zm({type:dy.GeneralString})],nS.prototype,"entrustVers",void 0),nb([Zm({type:iS})],nS.prototype,"entrustInfoFlags",void 0);let oS=sS=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,sS.prototype)}};oS=sS=nb([Xm({type:uy.Sequence,itemType:Fv})],oS);class aS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof aS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&zf(e.parameters,this.parameters)||e.parameters===this.parameters)}}nb([Zm({type:dy.ObjectIdentifier})],aS.prototype,"algorithm",void 0),nb([Zm({type:dy.Any,optional:!0})],aS.prototype,"parameters",void 0);class cS{constructor(e={}){this.algorithm=new aS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:aS})],cS.prototype,"algorithm",void 0),nb([Zm({type:dy.BitString})],cS.prototype,"subjectPublicKey",void 0);let lS=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){const t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};nb([Zm({type:dy.UTCTime})],lS.prototype,"utcTime",void 0),nb([Zm({type:dy.GeneralizedTime})],lS.prototype,"generalTime",void 0),lS=nb([Xm({type:uy.Choice})],lS);class hS{constructor(e){this.notBefore=new lS(new Date),this.notAfter=new lS(new Date),e&&(this.notBefore=new lS(e.notBefore),this.notAfter=new lS(e.notAfter))}}var uS;nb([Zm({type:lS})],hS.prototype,"notBefore",void 0),nb([Zm({type:lS})],hS.prototype,"notAfter",void 0);class dS{constructor(e={}){this.extnID="",this.critical=dS.CRITICAL,this.extnValue=new vm,Object.assign(this,e)}}dS.CRITICAL=!1,nb([Zm({type:dy.ObjectIdentifier})],dS.prototype,"extnID",void 0),nb([Zm({type:dy.Boolean,defaultValue:dS.CRITICAL})],dS.prototype,"critical",void 0),nb([Zm({type:vm})],dS.prototype,"extnValue",void 0);let gS=uS=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,uS.prototype)}};var fS;gS=uS=nb([Xm({type:uy.Sequence,itemType:dS})],gS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(fS||(fS={}));class pS{constructor(e={}){this.version=fS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new aS,this.issuer=new Bv,this.validity=new hS,this.subject=new Bv,this.subjectPublicKeyInfo=new cS,Object.assign(this,e)}}nb([Zm({type:dy.Integer,context:0,defaultValue:fS.v1})],pS.prototype,"version",void 0),nb([Zm({type:dy.Integer,converter:Cm})],pS.prototype,"serialNumber",void 0),nb([Zm({type:aS})],pS.prototype,"signature",void 0),nb([Zm({type:Bv})],pS.prototype,"issuer",void 0),nb([Zm({type:hS})],pS.prototype,"validity",void 0),nb([Zm({type:Bv})],pS.prototype,"subject",void 0),nb([Zm({type:cS})],pS.prototype,"subjectPublicKeyInfo",void 0),nb([Zm({type:dy.BitString,context:1,implicit:!0,optional:!0})],pS.prototype,"issuerUniqueID",void 0),nb([Zm({type:dy.BitString,context:2,implicit:!0,optional:!0})],pS.prototype,"subjectUniqueID",void 0),nb([Zm({type:gS,context:3,optional:!0})],pS.prototype,"extensions",void 0);class yS{constructor(e={}){this.tbsCertificate=new pS,this.signatureAlgorithm=new aS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:pS})],yS.prototype,"tbsCertificate",void 0),nb([Zm({type:aS})],yS.prototype,"signatureAlgorithm",void 0),nb([Zm({type:dy.BitString})],yS.prototype,"signatureValue",void 0);class mS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new lS,Object.assign(this,e)}}nb([Zm({type:dy.Integer,converter:Cm})],mS.prototype,"userCertificate",void 0),nb([Zm({type:lS})],mS.prototype,"revocationDate",void 0),nb([Zm({type:dS,optional:!0,repeated:"sequence"})],mS.prototype,"crlEntryExtensions",void 0);class bS{constructor(e={}){this.signature=new aS,this.issuer=new Bv,this.thisUpdate=new lS,Object.assign(this,e)}}nb([Zm({type:dy.Integer,optional:!0})],bS.prototype,"version",void 0),nb([Zm({type:aS})],bS.prototype,"signature",void 0),nb([Zm({type:Bv})],bS.prototype,"issuer",void 0),nb([Zm({type:lS})],bS.prototype,"thisUpdate",void 0),nb([Zm({type:lS,optional:!0})],bS.prototype,"nextUpdate",void 0),nb([Zm({type:mS,repeated:"sequence",optional:!0})],bS.prototype,"revokedCertificates",void 0),nb([Zm({type:dS,optional:!0,context:0,repeated:"sequence"})],bS.prototype,"crlExtensions",void 0);class AS{constructor(e={}){this.tbsCertList=new bS,this.signatureAlgorithm=new aS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:bS})],AS.prototype,"tbsCertList",void 0),nb([Zm({type:aS})],AS.prototype,"signatureAlgorithm",void 0),nb([Zm({type:dy.BitString})],AS.prototype,"signature",void 0);class IS{constructor(e={}){this.issuer=new Bv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:Bv})],IS.prototype,"issuer",void 0),nb([Zm({type:dy.Integer,converter:Cm})],IS.prototype,"serialNumber",void 0);let vS=class{constructor(e={}){Object.assign(this,e)}};var wS;nb([Zm({type:eS,context:0,implicit:!0})],vS.prototype,"subjectKeyIdentifier",void 0),nb([Zm({type:IS})],vS.prototype,"issuerAndSerialNumber",void 0),vS=nb([Xm({type:uy.Choice})],vS),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(wS||(wS={}));let SS=class extends aS{};SS=nb([Xm({type:uy.Sequence})],SS);let ES=class extends aS{};ES=nb([Xm({type:uy.Sequence})],ES);let CS=class extends aS{};CS=nb([Xm({type:uy.Sequence})],CS);let kS=class extends aS{};kS=nb([Xm({type:uy.Sequence})],kS);let xS=class extends aS{};xS=nb([Xm({type:uy.Sequence})],xS);let BS=class extends aS{};BS=nb([Xm({type:uy.Sequence})],BS);class _S{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var RS;nb([Zm({type:dy.ObjectIdentifier})],_S.prototype,"attrType",void 0),nb([Zm({type:dy.Any,repeated:"set"})],_S.prototype,"attrValues",void 0);class OS{constructor(e={}){this.version=wS.v0,this.sid=new vS,this.digestAlgorithm=new SS,this.signatureAlgorithm=new ES,this.signature=new vm,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],OS.prototype,"version",void 0),nb([Zm({type:vS})],OS.prototype,"sid",void 0),nb([Zm({type:SS})],OS.prototype,"digestAlgorithm",void 0),nb([Zm({type:_S,repeated:"set",context:0,implicit:!0,optional:!0})],OS.prototype,"signedAttrs",void 0),nb([Zm({type:ES})],OS.prototype,"signatureAlgorithm",void 0),nb([Zm({type:vm})],OS.prototype,"signature",void 0),nb([Zm({type:_S,repeated:"set",context:1,implicit:!0,optional:!0})],OS.prototype,"unsignedAttrs",void 0);let US=RS=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,RS.prototype)}};US=RS=nb([Xm({type:uy.Set,itemType:OS})],US);let TS=class extends lS{};TS=nb([Xm({type:uy.Choice})],TS);let NS=class extends OS{};NS=nb([Xm({type:uy.Sequence})],NS);class DS{constructor(e={}){this.acIssuer=new Uv,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var MS;nb([Zm({type:Uv})],DS.prototype,"acIssuer",void 0),nb([Zm({type:dy.Integer})],DS.prototype,"acSerial",void 0),nb([Zm({type:Jw,repeated:"sequence"})],DS.prototype,"attrs",void 0);let PS=MS=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,MS.prototype)}};PS=MS=nb([Xm({type:uy.Sequence,itemType:dy.ObjectIdentifier})],PS);class LS{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}nb([Zm({type:dy.Integer,optional:!0})],LS.prototype,"pathLenConstraint",void 0),nb([Zm({type:PS,implicit:!0,context:0,optional:!0})],LS.prototype,"permittedAttrs",void 0),nb([Zm({type:PS,implicit:!0,context:1,optional:!0})],LS.prototype,"excludedAttrs",void 0),nb([Zm({type:dy.Boolean,defaultValue:!0})],LS.prototype,"permitUnSpecified",void 0);class HS{constructor(e={}){this.issuer=new Yv,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var KS;nb([Zm({type:Yv})],HS.prototype,"issuer",void 0),nb([Zm({type:dy.Integer,converter:Cm})],HS.prototype,"serial",void 0),nb([Zm({type:dy.BitString,optional:!0})],HS.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(KS||(KS={}));class VS{constructor(e={}){this.digestedObjectType=KS.publicKey,this.digestAlgorithm=new aS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.Enumerated})],VS.prototype,"digestedObjectType",void 0),nb([Zm({type:dy.ObjectIdentifier,optional:!0})],VS.prototype,"otherObjectTypeID",void 0),nb([Zm({type:aS})],VS.prototype,"digestAlgorithm",void 0),nb([Zm({type:dy.BitString})],VS.prototype,"objectDigest",void 0);class QS{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:Yv,optional:!0})],QS.prototype,"issuerName",void 0),nb([Zm({type:HS,context:0,implicit:!0,optional:!0})],QS.prototype,"baseCertificateID",void 0),nb([Zm({type:VS,context:1,implicit:!0,optional:!0})],QS.prototype,"objectDigestInfo",void 0);let FS=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:Uv,repeated:"sequence"})],FS.prototype,"v1Form",void 0),nb([Zm({type:QS,context:0,implicit:!0})],FS.prototype,"v2Form",void 0),FS=nb([Xm({type:uy.Choice})],FS);class GS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}nb([Zm({type:dy.GeneralizedTime})],GS.prototype,"notBeforeTime",void 0),nb([Zm({type:dy.GeneralizedTime})],GS.prototype,"notAfterTime",void 0);class $S{constructor(e={}){Object.assign(this,e)}}var jS,qS,zS;nb([Zm({type:HS,implicit:!0,context:0,optional:!0})],$S.prototype,"baseCertificateID",void 0),nb([Zm({type:Yv,implicit:!0,context:1,optional:!0})],$S.prototype,"entityName",void 0),nb([Zm({type:VS,implicit:!0,context:2,optional:!0})],$S.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(jS||(jS={}));class WS{constructor(e={}){this.version=jS.v2,this.holder=new $S,this.issuer=new FS,this.signature=new aS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new GS,this.attributes=[],Object.assign(this,e)}}nb([Zm({type:dy.Integer})],WS.prototype,"version",void 0),nb([Zm({type:$S})],WS.prototype,"holder",void 0),nb([Zm({type:FS})],WS.prototype,"issuer",void 0),nb([Zm({type:aS})],WS.prototype,"signature",void 0),nb([Zm({type:dy.Integer,converter:Cm})],WS.prototype,"serialNumber",void 0),nb([Zm({type:GS})],WS.prototype,"attrCertValidityPeriod",void 0),nb([Zm({type:Jw,repeated:"sequence"})],WS.prototype,"attributes",void 0),nb([Zm({type:dy.BitString,optional:!0})],WS.prototype,"issuerUniqueID",void 0),nb([Zm({type:gS,optional:!0})],WS.prototype,"extensions",void 0);class JS{constructor(e={}){this.acinfo=new WS,this.signatureAlgorithm=new aS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:WS})],JS.prototype,"acinfo",void 0),nb([Zm({type:aS})],JS.prototype,"signatureAlgorithm",void 0),nb([Zm({type:dy.BitString})],JS.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(qS||(qS={}));class YS extends Im{}class XS{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier,implicit:!0,context:0})],XS.prototype,"type",void 0),nb([Zm({type:dy.Any,implicit:!0,context:1})],XS.prototype,"value",void 0);class ZS{constructor(e={}){this.policyId="",this.classList=new YS(qS.unclassified),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],ZS.prototype,"policyId",void 0),nb([Zm({type:YS,defaultValue:new YS(qS.unclassified)})],ZS.prototype,"classList",void 0),nb([Zm({type:XS,repeated:"set"})],ZS.prototype,"securityCategories",void 0);class eE{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:vm})],eE.prototype,"cotets",void 0),nb([Zm({type:dy.ObjectIdentifier})],eE.prototype,"oid",void 0),nb([Zm({type:dy.Utf8String})],eE.prototype,"string",void 0);class tE{constructor(e={}){this.values=[],Object.assign(this,e)}}nb([Zm({type:Yv,implicit:!0,context:0,optional:!0})],tE.prototype,"policyAuthority",void 0),nb([Zm({type:eE,repeated:"sequence"})],tE.prototype,"values",void 0);class rE{constructor(e={}){this.targetCertificate=new HS,Object.assign(this,e)}}nb([Zm({type:HS})],rE.prototype,"targetCertificate",void 0),nb([Zm({type:Uv,optional:!0})],rE.prototype,"targetName",void 0),nb([Zm({type:VS,optional:!0})],rE.prototype,"certDigestInfo",void 0);let sE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:Uv,context:0,implicit:!0})],sE.prototype,"targetName",void 0),nb([Zm({type:Uv,context:1,implicit:!0})],sE.prototype,"targetGroup",void 0),nb([Zm({type:rE,context:2,implicit:!0})],sE.prototype,"targetCert",void 0),sE=nb([Xm({type:uy.Choice})],sE);let iE=zS=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,zS.prototype)}};var nE;iE=zS=nb([Xm({type:uy.Sequence,itemType:sE})],iE);let oE=nE=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,nE.prototype)}};oE=nE=nb([Xm({type:uy.Sequence,itemType:iE})],oE);class aE{constructor(e={}){Object.assign(this,e)}}nb([Zm({type:Yv,implicit:!0,context:0,optional:!0})],aE.prototype,"roleAuthority",void 0),nb([Zm({type:Uv,implicit:!0,context:1})],aE.prototype,"roleName",void 0);class cE{constructor(e={}){this.service=new Uv,this.ident=new Uv,Object.assign(this,e)}}var lE;nb([Zm({type:Uv})],cE.prototype,"service",void 0),nb([Zm({type:Uv})],cE.prototype,"ident",void 0),nb([Zm({type:vm,optional:!0})],cE.prototype,"authInfo",void 0);class hE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],hE.prototype,"otherCertFormat",void 0),nb([Zm({type:dy.Any})],hE.prototype,"otherCert",void 0);let uE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:yS})],uE.prototype,"certificate",void 0),nb([Zm({type:JS,context:2,implicit:!0})],uE.prototype,"v2AttrCert",void 0),nb([Zm({type:hE,context:3,implicit:!0})],uE.prototype,"other",void 0),uE=nb([Xm({type:uy.Choice})],uE);let dE=lE=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,lE.prototype)}};dE=lE=nb([Xm({type:uy.Set,itemType:uE})],dE);class gE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],gE.prototype,"contentType",void 0),nb([Zm({type:dy.Any,context:0})],gE.prototype,"content",void 0);let fE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:vm})],fE.prototype,"single",void 0),nb([Zm({type:dy.Any})],fE.prototype,"any",void 0),fE=nb([Xm({type:uy.Choice})],fE);class pE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],pE.prototype,"eContentType",void 0),nb([Zm({type:fE,context:0,optional:!0})],pE.prototype,"eContent",void 0);let yE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:vm,context:0,implicit:!0,optional:!0})],yE.prototype,"value",void 0),nb([Zm({type:vm,converter:Rm,context:0,implicit:!0,optional:!0,repeated:"sequence"})],yE.prototype,"constructedValue",void 0),yE=nb([Xm({type:uy.Choice})],yE);class mE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new kS,Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],mE.prototype,"contentType",void 0),nb([Zm({type:kS})],mE.prototype,"contentEncryptionAlgorithm",void 0),nb([Zm({type:yE,optional:!0})],mE.prototype,"encryptedContent",void 0);class bE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var AE;nb([Zm({type:dy.ObjectIdentifier})],bE.prototype,"keyAttrId",void 0),nb([Zm({type:dy.Any,optional:!0})],bE.prototype,"keyAttr",void 0);class IE{constructor(e={}){this.subjectKeyIdentifier=new eS,Object.assign(this,e)}}nb([Zm({type:eS})],IE.prototype,"subjectKeyIdentifier",void 0),nb([Zm({type:dy.GeneralizedTime,optional:!0})],IE.prototype,"date",void 0),nb([Zm({type:bE,optional:!0})],IE.prototype,"other",void 0);let vE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:IE,context:0,implicit:!0,optional:!0})],vE.prototype,"rKeyId",void 0),nb([Zm({type:IS,optional:!0})],vE.prototype,"issuerAndSerialNumber",void 0),vE=nb([Xm({type:uy.Choice})],vE);class wE{constructor(e={}){this.rid=new vE,this.encryptedKey=new vm,Object.assign(this,e)}}nb([Zm({type:vE})],wE.prototype,"rid",void 0),nb([Zm({type:vm})],wE.prototype,"encryptedKey",void 0);let SE=AE=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,AE.prototype)}};SE=AE=nb([Xm({type:uy.Sequence,itemType:wE})],SE);class EE{constructor(e={}){this.algorithm=new aS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:aS})],EE.prototype,"algorithm",void 0),nb([Zm({type:dy.BitString})],EE.prototype,"publicKey",void 0);let CE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:eS,context:0,implicit:!0,optional:!0})],CE.prototype,"subjectKeyIdentifier",void 0),nb([Zm({type:EE,context:1,implicit:!0,optional:!0})],CE.prototype,"originatorKey",void 0),nb([Zm({type:IS,optional:!0})],CE.prototype,"issuerAndSerialNumber",void 0),CE=nb([Xm({type:uy.Choice})],CE);class kE{constructor(e={}){this.version=wS.v3,this.originator=new CE,this.keyEncryptionAlgorithm=new CS,this.recipientEncryptedKeys=new SE,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],kE.prototype,"version",void 0),nb([Zm({type:CE,context:0})],kE.prototype,"originator",void 0),nb([Zm({type:vm,context:1,optional:!0})],kE.prototype,"ukm",void 0),nb([Zm({type:CS})],kE.prototype,"keyEncryptionAlgorithm",void 0),nb([Zm({type:SE})],kE.prototype,"recipientEncryptedKeys",void 0);let xE=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:eS,context:0,implicit:!0})],xE.prototype,"subjectKeyIdentifier",void 0),nb([Zm({type:IS})],xE.prototype,"issuerAndSerialNumber",void 0),xE=nb([Xm({type:uy.Choice})],xE);class BE{constructor(e={}){this.version=wS.v0,this.rid=new xE,this.keyEncryptionAlgorithm=new CS,this.encryptedKey=new vm,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],BE.prototype,"version",void 0),nb([Zm({type:xE})],BE.prototype,"rid",void 0),nb([Zm({type:CS})],BE.prototype,"keyEncryptionAlgorithm",void 0),nb([Zm({type:vm})],BE.prototype,"encryptedKey",void 0);class _E{constructor(e={}){this.keyIdentifier=new vm,Object.assign(this,e)}}nb([Zm({type:vm})],_E.prototype,"keyIdentifier",void 0),nb([Zm({type:dy.GeneralizedTime,optional:!0})],_E.prototype,"date",void 0),nb([Zm({type:bE,optional:!0})],_E.prototype,"other",void 0);class RE{constructor(e={}){this.version=wS.v4,this.kekid=new _E,this.keyEncryptionAlgorithm=new CS,this.encryptedKey=new vm,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],RE.prototype,"version",void 0),nb([Zm({type:_E})],RE.prototype,"kekid",void 0),nb([Zm({type:CS})],RE.prototype,"keyEncryptionAlgorithm",void 0),nb([Zm({type:vm})],RE.prototype,"encryptedKey",void 0);class OE{constructor(e={}){this.version=wS.v0,this.keyEncryptionAlgorithm=new CS,this.encryptedKey=new vm,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],OE.prototype,"version",void 0),nb([Zm({type:BS,context:0,optional:!0})],OE.prototype,"keyDerivationAlgorithm",void 0),nb([Zm({type:CS})],OE.prototype,"keyEncryptionAlgorithm",void 0),nb([Zm({type:vm})],OE.prototype,"encryptedKey",void 0);class UE{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],UE.prototype,"oriType",void 0),nb([Zm({type:dy.Any})],UE.prototype,"oriValue",void 0);let TE=class{constructor(e={}){Object.assign(this,e)}};var NE;nb([Zm({type:BE,optional:!0})],TE.prototype,"ktri",void 0),nb([Zm({type:kE,context:1,implicit:!0,optional:!0})],TE.prototype,"kari",void 0),nb([Zm({type:RE,context:2,implicit:!0,optional:!0})],TE.prototype,"kekri",void 0),nb([Zm({type:OE,context:3,implicit:!0,optional:!0})],TE.prototype,"pwri",void 0),nb([Zm({type:UE,context:4,implicit:!0,optional:!0})],TE.prototype,"ori",void 0),TE=nb([Xm({type:uy.Choice})],TE);let DE=NE=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,NE.prototype)}};var ME;DE=NE=nb([Xm({type:uy.Set,itemType:TE})],DE);class PE{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],PE.prototype,"otherRevInfoFormat",void 0),nb([Zm({type:dy.Any})],PE.prototype,"otherRevInfo",void 0);let LE=class{constructor(e={}){this.other=new PE,Object.assign(this,e)}};nb([Zm({type:PE,context:1,implicit:!0})],LE.prototype,"other",void 0),LE=nb([Xm({type:uy.Choice})],LE);let HE=ME=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,ME.prototype)}};HE=ME=nb([Xm({type:uy.Set,itemType:LE})],HE);class KE{constructor(e={}){Object.assign(this,e)}}var VE;nb([Zm({type:dE,context:0,implicit:!0,optional:!0})],KE.prototype,"certs",void 0),nb([Zm({type:HE,context:1,implicit:!0,optional:!0})],KE.prototype,"crls",void 0);let QE=VE=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,VE.prototype)}};QE=VE=nb([Xm({type:uy.Set,itemType:_S})],QE);class FE{constructor(e={}){this.version=wS.v0,this.recipientInfos=new DE,this.encryptedContentInfo=new mE,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],FE.prototype,"version",void 0),nb([Zm({type:KE,context:0,implicit:!0,optional:!0})],FE.prototype,"originatorInfo",void 0),nb([Zm({type:DE})],FE.prototype,"recipientInfos",void 0),nb([Zm({type:mE})],FE.prototype,"encryptedContentInfo",void 0),nb([Zm({type:QE,context:1,implicit:!0,optional:!0})],FE.prototype,"unprotectedAttrs",void 0);const GE="1.2.840.113549.1.7.2";var $E;let jE=$E=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,$E.prototype)}};jE=$E=nb([Xm({type:uy.Set,itemType:SS})],jE);class qE{constructor(e={}){this.version=wS.v0,this.digestAlgorithms=new jE,this.encapContentInfo=new pE,this.signerInfos=new US,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],qE.prototype,"version",void 0),nb([Zm({type:jE})],qE.prototype,"digestAlgorithms",void 0),nb([Zm({type:pE})],qE.prototype,"encapContentInfo",void 0),nb([Zm({type:dE,context:0,implicit:!0,optional:!0})],qE.prototype,"certificates",void 0),nb([Zm({type:HE,context:1,implicit:!0,optional:!0})],qE.prototype,"crls",void 0),nb([Zm({type:US})],qE.prototype,"signerInfos",void 0);const zE="1.2.840.10045.2.1",WE="1.2.840.10045.4.1",JE="1.2.840.10045.4.3.1",YE="1.2.840.10045.4.3.2",XE="1.2.840.10045.4.3.3",ZE="1.2.840.10045.4.3.4",eC="1.2.840.10045.3.1.7",tC="1.3.132.0.34",rC="1.3.132.0.35";function sC(e){return new aS({algorithm:e})}const iC=sC(WE),nC=(sC(JE),sC(YE)),oC=sC(XE),aC=sC(ZE);let cC=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:dy.ObjectIdentifier})],cC.prototype,"fieldType",void 0),nb([Zm({type:dy.Any})],cC.prototype,"parameters",void 0),cC=nb([Xm({type:uy.Sequence})],cC);let lC=class{constructor(e={}){Object.assign(this,e)}};var hC;nb([Zm({type:dy.OctetString})],lC.prototype,"a",void 0),nb([Zm({type:dy.OctetString})],lC.prototype,"b",void 0),nb([Zm({type:dy.BitString,optional:!0})],lC.prototype,"seed",void 0),lC=nb([Xm({type:uy.Sequence})],lC),function(e){e[e.ecpVer1=1]="ecpVer1"}(hC||(hC={}));let uC=class{constructor(e={}){this.version=hC.ecpVer1,Object.assign(this,e)}};nb([Zm({type:dy.Integer})],uC.prototype,"version",void 0),nb([Zm({type:cC})],uC.prototype,"fieldID",void 0),nb([Zm({type:lC})],uC.prototype,"curve",void 0),nb([Zm({type:class extends vm{}})],uC.prototype,"base",void 0),nb([Zm({type:dy.Integer,converter:Cm})],uC.prototype,"order",void 0),nb([Zm({type:dy.Integer,optional:!0})],uC.prototype,"cofactor",void 0),uC=nb([Xm({type:uy.Sequence})],uC);let dC=class{constructor(e={}){Object.assign(this,e)}};nb([Zm({type:dy.ObjectIdentifier})],dC.prototype,"namedCurve",void 0),nb([Zm({type:dy.Null})],dC.prototype,"implicitCurve",void 0),nb([Zm({type:uC})],dC.prototype,"specifiedCurve",void 0),dC=nb([Xm({type:uy.Choice})],dC);class gC{constructor(e={}){this.version=1,this.privateKey=new vm,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],gC.prototype,"version",void 0),nb([Zm({type:vm})],gC.prototype,"privateKey",void 0),nb([Zm({type:dC,context:0,optional:!0})],gC.prototype,"parameters",void 0),nb([Zm({type:dy.BitString,context:1,optional:!0})],gC.prototype,"publicKey",void 0);class fC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.Integer,converter:Cm})],fC.prototype,"r",void 0),nb([Zm({type:dy.Integer,converter:Cm})],fC.prototype,"s",void 0);const pC="1.2.840.113549.1.1",yC=`${pC}.1`,mC=`${pC}.7`,bC=`${pC}.9`,AC=`${pC}.10`,IC=`${pC}.2`,vC=`${pC}.4`,wC=`${pC}.5`,SC=`${pC}.14`,EC=`${pC}.11`,CC=`${pC}.12`,kC=`${pC}.13`,xC=`${pC}.15`,BC=`${pC}.16`,_C="1.3.14.3.2.26",RC="2.16.840.1.101.3.4.2.4",OC="2.16.840.1.101.3.4.2.1",UC="2.16.840.1.101.3.4.2.2",TC="2.16.840.1.101.3.4.2.3",NC=`${pC}.8`;function DC(e){return new aS({algorithm:e,parameters:null})}DC("1.2.840.113549.2.2"),DC("1.2.840.113549.2.5");const MC=DC(_C),PC=(DC(RC),DC(OC),DC(UC),DC(TC),DC("2.16.840.1.101.3.4.2.5"),DC("2.16.840.1.101.3.4.2.6"),new aS({algorithm:NC,parameters:ib.serialize(MC)})),LC=new aS({algorithm:bC,parameters:ib.serialize(_m.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});DC(yC),DC(IC),DC(vC),DC(wC),DC(xC),DC(BC),DC(CC),DC(kC),DC(xC),DC(BC);class HC{constructor(e={}){this.hashAlgorithm=new aS(MC),this.maskGenAlgorithm=new aS({algorithm:NC,parameters:ib.serialize(MC)}),this.pSourceAlgorithm=new aS(LC),Object.assign(this,e)}}nb([Zm({type:aS,context:0,defaultValue:MC})],HC.prototype,"hashAlgorithm",void 0),nb([Zm({type:aS,context:1,defaultValue:PC})],HC.prototype,"maskGenAlgorithm",void 0),nb([Zm({type:aS,context:2,defaultValue:LC})],HC.prototype,"pSourceAlgorithm",void 0),new aS({algorithm:mC,parameters:ib.serialize(new HC)});class KC{constructor(e={}){this.hashAlgorithm=new aS(MC),this.maskGenAlgorithm=new aS({algorithm:NC,parameters:ib.serialize(MC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}nb([Zm({type:aS,context:0,defaultValue:MC})],KC.prototype,"hashAlgorithm",void 0),nb([Zm({type:aS,context:1,defaultValue:PC})],KC.prototype,"maskGenAlgorithm",void 0),nb([Zm({type:dy.Integer,context:2,defaultValue:20})],KC.prototype,"saltLength",void 0),nb([Zm({type:dy.Integer,context:3,defaultValue:1})],KC.prototype,"trailerField",void 0),new aS({algorithm:AC,parameters:ib.serialize(new KC)});class VC{constructor(e={}){this.digestAlgorithm=new aS,this.digest=new vm,Object.assign(this,e)}}var QC;nb([Zm({type:aS})],VC.prototype,"digestAlgorithm",void 0),nb([Zm({type:vm})],VC.prototype,"digest",void 0);class FC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.Integer,converter:Cm})],FC.prototype,"prime",void 0),nb([Zm({type:dy.Integer,converter:Cm})],FC.prototype,"exponent",void 0),nb([Zm({type:dy.Integer,converter:Cm})],FC.prototype,"coefficient",void 0);let GC=QC=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,QC.prototype)}};GC=QC=nb([Xm({type:uy.Sequence,itemType:FC})],GC);class $C{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.Integer})],$C.prototype,"version",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"modulus",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"publicExponent",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"privateExponent",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"prime1",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"prime2",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"exponent1",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"exponent2",void 0),nb([Zm({type:dy.Integer,converter:Cm})],$C.prototype,"coefficient",void 0),nb([Zm({type:GC,optional:!0})],$C.prototype,"otherPrimeInfos",void 0);class jC{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var qC;nb([Zm({type:dy.Integer,converter:Cm})],jC.prototype,"modulus",void 0),nb([Zm({type:dy.Integer,converter:Cm})],jC.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(qC||(qC={}));const zC=qC;var WC=function(e,t){return WC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},WC(e,t)};function JC(e,t){function r(){this.constructor=e}WC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function YC(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function XC(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function ZC(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(XC(arguments[t]));return e}function ek(e){return!!e.useClass}function tk(e){return!!e.useFactory}var rk=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,s=!1;return new Proxy({},this.createHandler(function(){return s||(t=e(r.wrap()),s=!0),t}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(r){t[r]=function(){for(var t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t[0]=e(),Reflect[r].apply(void 0,ZC(t))}}),t},e}();function sk(e){return"string"==typeof e||"symbol"==typeof e}function ik(e){return"object"==typeof e&&"token"in e&&"transform"in e}function nk(e){return!!e.useToken}function ok(e){return null!=e.useValue}var ak=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}();const ck=ak,lk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return JC(t,e),t}(ck),hk=function(){this.scopedResolutions=new Map};var uk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return JC(t,e),t}(ck),dk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return JC(t,e),t}(ck);const gk=function(){this.preResolution=new uk,this.postResolution=new dk};var fk=new Map,pk=function(){function e(e){this.parent=e,this._registry=new lk,this.interceptors=new gk,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:zC.Transient}),this.ensureNotDisposed(),s=function(e){return ek(e)||ok(e)||nk(e)||tk(e)}(t)?t:{useClass:t},nk(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+ZC(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&nk(a.provider)?a.provider:null}if((r.lifecycle===zC.Singleton||r.lifecycle==zC.ContainerScoped||r.lifecycle==zC.ResolutionScoped)&&(ok(s)||tk(s)))throw new Error('Cannot use lifecycle "'+zC[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),sk(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),sk(e)){if(sk(t))return this.register(e,{useToken:t},{lifecycle:zC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:zC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!sk(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:zC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new hk),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&sk(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var i=this.resolveRegistration(s,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof rk}(e))return i=this.construct(e,t),this.executePostResolutionInterceptor(e,i,"Single"),i;throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,s;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var n=YC(this.interceptors.preResolution.getAll(e)),o=n.next();!o.done;o=n.next()){var a=o.value;"Once"!=a.options.frequency&&i.push(a),a.callback(e,t)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var s,i;if(this.interceptors.postResolution.has(e)){var n=[];try{for(var o=YC(this.interceptors.postResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===zC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===zC.Singleton,i=e.options.lifecycle===zC.ContainerScoped,n=s||i;return r=ok(e.provider)?e.provider.useValue:nk(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):ek(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):tk(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===zC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new hk),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&sk(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var n=i.map(function(e){return s.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,n,"All"),n}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,"All"),o},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=YC(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=XC(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!ok(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var s=new e(this);try{for(var i=YC(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=XC(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===zC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===zC.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,s&&(i=2&n[0]?s.return:n[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,n[1])).done)return i;switch(s=0,i&&(n=[2&n[0],i.value]),n[0]){case 0:case 1:i=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){o.label=n[1];break}if(6===n[0]&&o.label<i[1]){o.label=i[1],i=n;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(n);break}i[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(e){n=[6,e],s=0}finally{r=i=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}}(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var r=t.dispose();r&&e.push(r)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof rk)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=fk.get(e);if(!s||0===s.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(r.resolveParams(t,e));return new(e.bind.apply(e,ZC([void 0],i)))}();return"function"!=typeof(s=i).dispose||s.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(s,i){var n,o,a,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?ik(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,ZC([r.resolveAll(s.token,new hk,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,ZC([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new hk,s.isOptional):r.resolve(s.token,e,s.isOptional):ik(s)?(a=r.resolve(s.transform,e)).transform.apply(a,ZC([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=XC(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),ZC([e],t.message.split("\n").map(function(e){return r+e})).join("\n")}("Cannot inject the dependency "+(i=t,(null===(s=void 0===n?null:n)?"at position #"+i:'"'+s.split(",")[i].trim()+'" at position #'+i)+' of "')+e.name+'" constructor. Reason:',r)}(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),yk=new pk;const mk=function(e){return function(t){fk.set(t,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach(function(e){t[+e]=r[e]}),t}(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){yk.register(e,t)}):yk.register(e.token,t))}};if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");var bk;class Ak{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}nb([Zm({type:dy.ObjectIdentifier})],Ak.prototype,"attrId",void 0),nb([Zm({type:dy.Any,repeated:"set"})],Ak.prototype,"attrValues",void 0);let Ik=bk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,bk.prototype)}};var vk;Ik=bk=nb([Xm({type:uy.Sequence,itemType:Ak})],Ik);let wk=vk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,vk.prototype)}};wk=vk=nb([Xm({type:uy.Sequence,itemType:gE})],wk);class Sk{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Sk.prototype,"certId",void 0),nb([Zm({type:dy.Any,context:0})],Sk.prototype,"certValue",void 0);class Ek{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Ek.prototype,"crlId",void 0),nb([Zm({type:dy.Any,context:0})],Ek.prototype,"crltValue",void 0);class Ck extends vm{}class kk{constructor(e={}){this.encryptionAlgorithm=new aS,this.encryptedData=new Ck,Object.assign(this,e)}}var xk,Bk;nb([Zm({type:aS})],kk.prototype,"encryptionAlgorithm",void 0),nb([Zm({type:Ck})],kk.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(Bk||(Bk={}));class _k extends vm{}let Rk=xk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,xk.prototype)}};Rk=xk=nb([Xm({type:uy.Sequence,itemType:Jw})],Rk);class Ok{constructor(e={}){this.version=Bk.v1,this.privateKeyAlgorithm=new aS,this.privateKey=new _k,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],Ok.prototype,"version",void 0),nb([Zm({type:aS})],Ok.prototype,"privateKeyAlgorithm",void 0),nb([Zm({type:_k})],Ok.prototype,"privateKey",void 0),nb([Zm({type:Rk,implicit:!0,context:0,optional:!0})],Ok.prototype,"attributes",void 0);let Uk=class extends Ok{};Uk=nb([Xm({type:uy.Sequence})],Uk);let Tk=class extends kk{};Tk=nb([Xm({type:uy.Sequence})],Tk);class Nk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Nk.prototype,"secretTypeId",void 0),nb([Zm({type:dy.Any,context:0})],Nk.prototype,"secretValue",void 0);class Dk{constructor(e={}){this.mac=new VC,this.macSalt=new vm,this.iterations=1,Object.assign(this,e)}}nb([Zm({type:VC})],Dk.prototype,"mac",void 0),nb([Zm({type:vm})],Dk.prototype,"macSalt",void 0),nb([Zm({type:dy.Integer,defaultValue:1})],Dk.prototype,"iterations",void 0);class Mk{constructor(e={}){this.version=3,this.authSafe=new gE,this.macData=new Dk,Object.assign(this,e)}}var Pk;nb([Zm({type:dy.Integer})],Mk.prototype,"version",void 0),nb([Zm({type:gE})],Mk.prototype,"authSafe",void 0),nb([Zm({type:Dk,optional:!0})],Mk.prototype,"macData",void 0);class Lk{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:dy.ObjectIdentifier})],Lk.prototype,"bagId",void 0),nb([Zm({type:dy.Any,context:0})],Lk.prototype,"bagValue",void 0),nb([Zm({type:Ak,repeated:"set",optional:!0})],Lk.prototype,"bagAttributes",void 0);let Hk=Pk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Pk.prototype)}};var Kk,Vk,Qk;Hk=Pk=nb([Xm({type:uy.Sequence,itemType:Lk})],Hk);const Fk="1.2.840.113549.1.9",Gk=`${Fk}.7`,$k=`${Fk}.14`;let jk=class extends Sv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};nb([Zm({type:dy.IA5String})],jk.prototype,"ia5String",void 0),jk=nb([Xm({type:uy.Choice})],jk);let qk=class extends gE{};qk=nb([Xm({type:uy.Sequence})],qk);let zk=class extends Mk{};zk=nb([Xm({type:uy.Sequence})],zk);let Wk=class extends kk{};Wk=nb([Xm({type:uy.Sequence})],Wk);let Jk=class{constructor(e=""){this.value=e}toString(){return this.value}};nb([Zm({type:dy.IA5String})],Jk.prototype,"value",void 0),Jk=nb([Xm({type:uy.Choice})],Jk);let Yk=class extends jk{};Yk=nb([Xm({type:uy.Choice})],Yk);let Xk=class extends Sv{};Xk=nb([Xm({type:uy.Choice})],Xk);let Zk=class{constructor(e=new Date){this.value=e}};nb([Zm({type:dy.GeneralizedTime})],Zk.prototype,"value",void 0),Zk=nb([Xm({type:uy.Choice})],Zk);let ex=class extends Sv{};ex=nb([Xm({type:uy.Choice})],ex);let tx=class{constructor(e="M"){this.value=e}toString(){return this.value}};nb([Zm({type:dy.PrintableString})],tx.prototype,"value",void 0),tx=nb([Xm({type:uy.Choice})],tx);let rx=class{constructor(e=""){this.value=e}toString(){return this.value}};nb([Zm({type:dy.PrintableString})],rx.prototype,"value",void 0),rx=nb([Xm({type:uy.Choice})],rx);let sx=class extends rx{};sx=nb([Xm({type:uy.Choice})],sx);let ix=class extends Sv{};ix=nb([Xm({type:uy.Choice})],ix);let nx=class{constructor(e=""){this.value=e}toString(){return this.value}};nb([Zm({type:dy.ObjectIdentifier})],nx.prototype,"value",void 0),nx=nb([Xm({type:uy.Choice})],nx);let ox=class extends lS{};ox=nb([Xm({type:uy.Choice})],ox);let ax=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};nb([Zm({type:dy.Integer})],ax.prototype,"value",void 0),ax=nb([Xm({type:uy.Choice})],ax);let cx=class extends OS{};cx=nb([Xm({type:uy.Sequence})],cx);let lx=class extends Sv{};lx=nb([Xm({type:uy.Choice})],lx);let hx=Kk=class extends gS{constructor(e){super(e),Object.setPrototypeOf(this,Kk.prototype)}};hx=Kk=nb([Xm({type:uy.Sequence})],hx);let ux=Vk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Vk.prototype)}};ux=Vk=nb([Xm({type:uy.Set,itemType:_S})],ux);let dx=class{constructor(e=""){this.value=e}toString(){return this.value}};nb([Zm({type:dy.BmpString})],dx.prototype,"value",void 0),dx=nb([Xm({type:uy.Choice})],dx);let gx=class extends aS{};gx=nb([Xm({type:uy.Sequence})],gx);let fx=Qk=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,Qk.prototype)}};var px;fx=Qk=nb([Xm({type:uy.Sequence,itemType:gx})],fx);let yx=px=class extends sb{constructor(e){super(e),Object.setPrototypeOf(this,px.prototype)}};yx=px=nb([Xm({type:uy.Sequence,itemType:Jw})],yx);class mx{constructor(e={}){this.version=0,this.subject=new Bv,this.subjectPKInfo=new cS,this.attributes=new yx,Object.assign(this,e)}}nb([Zm({type:dy.Integer})],mx.prototype,"version",void 0),nb([Zm({type:Bv})],mx.prototype,"subject",void 0),nb([Zm({type:cS})],mx.prototype,"subjectPKInfo",void 0),nb([Zm({type:yx,implicit:!0,context:0})],mx.prototype,"attributes",void 0);class bx{constructor(e={}){this.certificationRequestInfo=new mx,this.signatureAlgorithm=new aS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}nb([Zm({type:mx})],bx.prototype,"certificationRequestInfo",void 0),nb([Zm({type:aS})],bx.prototype,"signatureAlgorithm",void 0),nb([Zm({type:dy.BitString})],bx.prototype,"signature",void 0);const Ax="crypto.algorithm",Ix="crypto.algorithmProvider";var vx;yk.registerSingleton(Ix,class{getAlgorithms(){return yk.resolveAll(Ax)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new aS({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const wx="1.3.36.3.3.2.8.1.1",Sx=`${wx}.1`,Ex=`${wx}.2`,Cx=`${wx}.3`,kx=`${wx}.4`,xx=`${wx}.5`,Bx=`${wx}.6`,_x=`${wx}.7`,Rx=`${wx}.8`,Ox=`${wx}.9`,Ux=`${wx}.10`,Tx=`${wx}.11`,Nx=`${wx}.12`,Dx=`${wx}.13`,Mx=`${wx}.14`,Px="brainpoolP160r1",Lx="brainpoolP160t1",Hx="brainpoolP192r1",Kx="brainpoolP192t1",Vx="brainpoolP224r1",Qx="brainpoolP224t1",Fx="brainpoolP256r1",Gx="brainpoolP256t1",$x="brainpoolP320r1",jx="brainpoolP320t1",qx="brainpoolP384r1",zx="brainpoolP384t1",Wx="brainpoolP512r1",Jx="brainpoolP512t1",Yx="ECDSA";let Xx=vx=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Yx.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return iC;case"sha-256":return nC;case"sha-384":return oC;case"sha-512":return aC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=eC;break;case"K-256":t=vx.SECP256K1;break;case"P-384":t=tC;break;case"P-521":t=rC;break;case Px:t=Sx;break;case Lx:t=Ex;break;case Hx:t=Cx;break;case Kx:t=kx;break;case Vx:t=xx;break;case Qx:t=Bx;break;case Fx:t=_x;break;case Gx:t=Rx;break;case $x:t=Ox;break;case jx:t=Ux;break;case qx:t=Tx;break;case zx:t=Nx;break;case Wx:t=Dx;break;case Jx:t=Mx}if(t)return new aS({algorithm:zE,parameters:ib.serialize(new dC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case WE:return{name:Yx,hash:{name:"SHA-1"}};case YE:return{name:Yx,hash:{name:"SHA-256"}};case XE:return{name:Yx,hash:{name:"SHA-384"}};case ZE:return{name:Yx,hash:{name:"SHA-512"}};case zE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(ib.parse(e.parameters,dC).namedCurve){case eC:return{name:Yx,namedCurve:"P-256"};case vx.SECP256K1:return{name:Yx,namedCurve:"K-256"};case tC:return{name:Yx,namedCurve:"P-384"};case rC:return{name:Yx,namedCurve:"P-521"};case Sx:return{name:Yx,namedCurve:Px};case Ex:return{name:Yx,namedCurve:Lx};case Cx:return{name:Yx,namedCurve:Hx};case kx:return{name:Yx,namedCurve:Kx};case xx:return{name:Yx,namedCurve:Vx};case Bx:return{name:Yx,namedCurve:Qx};case _x:return{name:Yx,namedCurve:Fx};case Rx:return{name:Yx,namedCurve:Gx};case Ox:return{name:Yx,namedCurve:$x};case Ux:return{name:Yx,namedCurve:jx};case Tx:return{name:Yx,namedCurve:qx};case Nx:return{name:Yx,namedCurve:zx};case Dx:return{name:Yx,namedCurve:Wx};case Mx:return{name:Yx,namedCurve:Jx}}}return null}};Xx.SECP256K1="1.3.132.0.10",Xx=vx=nb([mk()],Xx),yk.registerSingleton(Ax,Xx);const Zx=Symbol("name"),eB=Symbol("value");class tB{constructor(e,t={},r=""){this[Zx]=e,this[eB]=r;for(const e in t)this[e]=t[e]}}tB.NAME=Zx,tB.VALUE=eB;class rB{static toString(e){return this.items[e]||e}}rB.items={[_C]:"sha1",[RC]:"sha224",[OC]:"sha256",[UC]:"sha384",[TC]:"sha512",[yC]:"rsaEncryption",[wC]:"sha1WithRSAEncryption",[SC]:"sha224WithRSAEncryption",[EC]:"sha256WithRSAEncryption",[CC]:"sha384WithRSAEncryption",[kC]:"sha512WithRSAEncryption",[zE]:"ecPublicKey",[WE]:"ecdsaWithSHA1",[JE]:"ecdsaWithSHA224",[YE]:"ecdsaWithSHA256",[XE]:"ecdsaWithSHA384",[ZE]:"ecdsaWithSHA512",[kw]:"TLS WWW server authentication",[xw]:"TLS WWW client authentication",[Bw]:"Code Signing",[_w]:"E-mail Protection",[Rw]:"Time Stamping",[Ow]:"OCSP Signing",[GE]:"Signed Data"};class sB{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let s=this.pad(t++),i="";const n=e[tB.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[tB.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],o=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${o}${n}`);else if(n instanceof Date)r.push(`${s}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[tB.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof tB)n[tB.NAME]=i,r.push(...this.serializeObj(n,t));else if(Hf.isBufferSource(n))i?(r.push(`${s}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[tB.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=Hf.toUint8Array(e),i=[];for(let e=0;e<s.length;){const t=[];for(let r=0;r<16&&e<s.length;r++){8===r&&t.push("");const i=s[e++].toString(16).padStart(2,"0");t.push(i)}i.push(`${r}${t.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}sB.oidSerializer=rB,sB.algorithmSerializer=class{static toTextObject(e){const t=new tB("Algorithm Identifier",{},rB.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case zE:{const r=(new Xx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class iB{constructor(...e){if(1===e.length){const t=e[0];this.rawData=ib.serialize(t),this.onInit(t)}else{const t=ib.parse(e[0],e[1]);this.rawData=Hf.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof iB&&zf(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return ib.toString(this.rawData);case"text":return sB.serialize(this.toTextObject());case"hex":return jf.ToHex(this.rawData);case"base64":return jf.ToBase64(this.rawData);case"base64url":return jf.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new tB(this.getTextName(),{},e)}}iB.NAME="ASN";class nB extends iB{constructor(...e){let t;t=Hf.isBufferSource(e[0])?Hf.toArrayBuffer(e[0]):ib.serialize(new dS({extnID:e[0],critical:e[1],extnValue:new vm(Hf.toArrayBuffer(e[2]))})),super(t,dS)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[tB.NAME]===nB.NAME&&(e[tB.NAME]=rB.toString(this.type)),e}}var oB;class aB{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[oB]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(aB.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(aB.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=aB.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(aB.DEFAULT,e);return this}}oB=Symbol.toStringTag,aB.DEFAULT="default";const cB=new aB,lB=/^[0-2](?:\.[1-9][0-9]*)+$/;class hB{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(lB).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const uB=new hB;function dB(e,t){return`\\${jf.ToHex(jf.FromUtf8String(t)).toUpperCase()}`}uB.register("CN","2.5.4.3"),uB.register("L","2.5.4.7"),uB.register("ST","2.5.4.8"),uB.register("O","2.5.4.10"),uB.register("OU","2.5.4.11"),uB.register("C","2.5.4.6"),uB.register("DC","0.9.2342.19200300.100.1.25"),uB.register("E","1.2.840.113549.1.9.1"),uB.register("G","2.5.4.42"),uB.register("I","2.5.4.43"),uB.register("SN","2.5.4.4"),uB.register("T","2.5.4.12");class gB{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new hB,this.asn=new Bv;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const r=t[e];this.extraNames.register(e,r)}"string"==typeof e?this.asn=this.fromString(e):e instanceof Bv?this.asn=e:Hf.isBufferSource(e)?this.asn=ib.parse(e,Bv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||uB.findId(e),r=[];for(const e of this.asn)for(const s of e)s.type===t&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||uB.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${jf.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,dB)}`).join("+")).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const s={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=s[r])&&void 0!==e||(s[r]=[]),s[r].push(t.value.anyValue?`#${jf.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new Bv,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,i=",";for(;s=r.exec(`${e},`);){let[,e,r]=s;const n=r[r.length-1];","!==n&&"+"!==n||(r=r.slice(0,r.length-1),s[3]=n);const o=s[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===i?t[t.length-1].push(a):t.push(new kv([a])),i=o}return t}fromJSON(e){const t=new Bv;for(const r of e){const e=new kv;for(const t in r){const s=this.getTypeOid(t),i=r[t];for(const t of i){const r=this.createAttribute(s,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new Cv({type:e});if("object"==typeof t)for(const e in t)switch(e){case"ia5String":r.value.ia5String=t[e];break;case"utf8String":r.value.utf8String=t[e];break;case"universalString":r.value.universalString=t[e];break;case"bmpString":r.value.bmpString=t[e];break;case"printableString":r.value.printableString=t[e]}else if("#"===t[0])r.value.anyValue=jf.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:gB.isPrintableString(s)?r.value.printableString=s:r.value.utf8String=s}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return ib.serialize(this.asn)}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||cB.get()):r=e[0]||cB.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const fB="Cannot initialize GeneralName from ASN.1 data.",pB=`${fB} Unsupported string format in use.`,yB=`${fB} Value doesn't match to GUID regular expression.`,mB=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,bB="1.3.6.1.4.1.311.25.1",AB="1.3.6.1.4.1.311.20.2.3",IB="dns",vB="dn",wB="email",SB="ip",EB="url",CB="guid",kB="upn",xB="id";class BB extends iB{constructor(...e){let t;if(2===e.length)switch(e[0]){case vB:{const r=new gB(e[1]).toArrayBuffer(),s=ib.parse(r,Bv);t=new Uv({directoryName:s});break}case IB:t=new Uv({dNSName:e[1]});break;case wB:t=new Uv({rfc822Name:e[1]});break;case CB:{const r=new RegExp(mB,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=r.slice(1).map((e,t)=>t<3?jf.ToHex(new Uint8Array(jf.FromHex(e)).reverse()):e).join("");t=new Uv({otherName:new Rv({typeId:bB,value:ib.serialize(new vm(jf.FromHex(s)))})});break}case SB:t=new Uv({iPAddress:e[1]});break;case xB:t=new Uv({registeredID:e[1]});break;case kB:t=new Uv({otherName:new Rv({typeId:AB,value:ib.serialize(Um.toASN(e[1]))})});break;case EB:t=new Uv({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=Hf.isBufferSource(e[0])?ib.parse(e[0],Uv):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=IB,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=wB,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=SB,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=EB,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=xB,this.value=e.registeredID;else if(null!=e.directoryName)this.type=vB,this.value=new gB(e.directoryName).toString();else{if(null==e.otherName)throw new Error(pB);if(e.otherName.typeId===bB){this.type=CB;const t=ib.parse(e.otherName.value,vm),r=new RegExp(mB,"i").exec(jf.ToHex(t));if(!r)throw new Error(yB);this.value=r.slice(1).map((e,t)=>t<3?jf.ToHex(new Uint8Array(jf.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==AB)throw new Error(pB);this.type=kB,this.value=ib.parse(e.otherName.value,Sv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case vB:case IB:case CB:case SB:case xB:case kB:case EB:e=this.type.toUpperCase();break;case wB:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===xB&&(t=rB.toString(t)),new tB(e,void 0,t)}}class _B extends iB{constructor(e){let t;if(e instanceof Yv)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof Uv)r.push(t);else{const e=ib.parse(new BB(t.type,t.value).rawData,Uv);r.push(e)}t=new Yv(r)}else{if(!Hf.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=ib.parse(e,Yv)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new BB(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let s=e[r[tB.NAME]];Array.isArray(s)||(s=[],e[r[tB.NAME]]=s),s.push(r)}return e}}_B.NAME="GeneralNames";const RB="-{5}",OB="\\n",UB="\\n",TB=`${RB}BEGIN ([^${OB}]+(?=${RB}))${RB}${UB}(?:((?:[^:${OB}]+: (?:[^${OB}]+${UB}(?: +[^${OB}]+${UB})*))+))?${UB}?((?:[a-zA-Z0-9=+/]+${UB})+)${RB}END \\1${RB}`;class NB{static isPem(e){return"string"==typeof e&&new RegExp(TB,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(TB,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${OB}]+`,"g"),""),t={type:s[1],headers:[],rawData:jf.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(UB,"g"));let r=null;for(const s of e){const[e,i]=s.split(/:(.*)/);if(void 0===i){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:i.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach(e=>{if(!Hf.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:Hf.toArrayBuffer(e)}))}):e.forEach(e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))}),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:Hf.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)s.push(`${t.key}: ${t.value}`);s.push("")}const i=jf.ToBase64(e.rawData);let n,o=0;const a=Array();for(;o<i.length&&(i.length-o<64?n=i.substring(o):(n=i.substring(o,o+64),o+=64),0!==n.length)&&(a.push(n),!(n.length<64)););return s.push(...a),s.push(`-----END ${r}-----`),s.join("\n")}}NB.CertificateTag="CERTIFICATE",NB.CrlTag="CRL",NB.CertificateRequestTag="CERTIFICATE REQUEST",NB.PublicKeyTag="PUBLIC KEY",NB.PrivateKeyTag="PRIVATE KEY";class DB extends iB{static isAsnEncoded(e){return Hf.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(NB.isPem(e))return NB.decode(e)[0];if(jf.isHex(e))return jf.FromHex(e);if(jf.isBase64(e))return jf.FromBase64(e);if(jf.isBase64Url(e))return jf.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=jf.ToBinary(e);return NB.isPem(t)?NB.decode(t)[0]:jf.isHex(t)?jf.FromHex(t):jf.isBase64(t)?jf.FromBase64(t):jf.isBase64Url(t)?jf.FromBase64Url(t):Hf.toArrayBuffer(e)}}constructor(...e){DB.isAsnEncoded(e[0])?super(DB.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?NB.encode(this.rawData,this.tag):super.toString(e)}}class MB extends DB{static async create(e,t=cB.get()){if(e instanceof MB)return e;if(aB.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new MB(r)}if(e.publicKey)return e.publicKey;if(Hf.isBufferSource(e))return new MB(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){DB.isAsnEncoded(e)?super(e,cS):super(e),this.tag=NB.PublicKeyTag}async export(...e){let t,r=["verify"],s={hash:"SHA-256",...this.algorithm};e.length>1?(s=e[0]||s,r=e[1]||r,t=e[2]||cB.get()):t=e[0]||cB.get();let i=this.rawData;const n=ib.parse(this.rawData,cS);return n.algorithm.algorithm===AC&&(i=function(e){return e.algorithm=new aS({algorithm:yC,parameters:null}),ib.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=yk.resolve(Ix),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case yC:{const t=ib.parse(e.subjectPublicKey,jC),s=Hf.toUint8Array(t.modulus);r.publicExponent=Hf.toUint8Array(t.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||cB.get()):r=e[0]||cB.get(),await r.subtle.digest(s,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=cB.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=cB.get();const s=ib.parse(this.rawData,cS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=ib.parse(this.rawData,cS);return e.Algorithm=sB.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===zE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class PB extends nB{static async create(e,t=!1,r=cB.get()){if("name"in e&&"serialNumber"in e)return new PB(e,t);const s=await MB.create(e,r),i=await s.getKeyIdentifier(r);return new PB(jf.ToHex(i),t)}constructor(...e){if(Hf.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new qv({keyIdentifier:new jv(jf.FromHex(e[0]))});super($v,e[1],ib.serialize(t))}else{const t=e[0],r=t.name instanceof _B?ib.parse(t.name.rawData,Yv):t.name,s=new qv({authorityCertIssuer:r,authorityCertSerialNumber:jf.FromHex(t.serialNumber)});super($v,e[1],ib.serialize(s))}}onInit(e){super.onInit(e);const t=ib.parse(e.extnValue,qv);t.keyIdentifier&&(this.keyId=jf.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?jf.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ib.parse(this.value,qv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new _B(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}PB.NAME="Authority Key Identifier";class LB extends nB{constructor(...e){if(Hf.isBufferSource(e[0])){super(e[0]);const t=ib.parse(this.value,Wv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Wv({cA:e[0],pathLenConstraint:e[1]});super(zv,e[2],ib.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var HB,KB;LB.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(HB||(HB={}));class VB extends nB{constructor(...e){if(Hf.isBufferSource(e[0])){super(e[0]);const t=ib.parse(this.value,Cw);this.usages=t.map(e=>e)}else{const t=new Cw(e[0]);super(Ew,e[1],ib.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>rB.toString(e)).join(", "),e}}VB.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(KB||(KB={}));class QB extends nB{constructor(...e){if(Hf.isBufferSource(e[0])){super(e[0]);const t=ib.parse(this.value,Hw);this.usages=t.toNumber()}else{const t=new Hw(e[0]);super(Mw,e[1],ib.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ib.parse(this.value,Hw);return e[""]=t.toJSON().join(", "),e}}QB.NAME="Key Usages";class FB extends nB{static async create(e,t=!1,r=cB.get()){const s=await MB.create(e,r),i=await s.getKeyIdentifier(r);return new FB(jf.ToHex(i),t)}constructor(...e){if(Hf.isBufferSource(e[0])){super(e[0]);const t=ib.parse(this.value,eS);this.keyId=jf.ToHex(t)}else{const t="string"==typeof e[0]?jf.FromHex(e[0]):e[0],r=new eS(t);super(Zw,e[1],ib.serialize(r)),this.keyId=jf.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ib.parse(this.value,eS);return e[""]=t,e}}FB.NAME="Subject Key Identifier";class GB extends nB{constructor(...e){Hf.isBufferSource(e[0])?super(e[0]):super(zw,e[1],new _B(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=ib.parse(e.extnValue,Ww);this.names=new _B(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}GB.NAME="Subject Alternative Name";class $B{static register(e,t){this.items.set(e,t)}static create(e){const t=new nB(e),r=this.items.get(t.type);return r?new r(e):t}}$B.items=new Map;class jB extends nB{constructor(...e){var t;if(Hf.isBufferSource(e[0])){super(e[0]);const t=ib.parse(this.value,cw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new cw(r.map(e=>new aw({policyIdentifier:e})));super(tw,s,ib.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new tB("",{},rB.toString(e))),e}}jB.NAME="Certificate Policies",$B.register(tw,jB);class qB extends nB{constructor(...e){var t;if(Hf.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new yw({distributionPoint:new pw({fullName:[new Uv({uniformResourceIdentifier:e})]})})),r=new mw(t);super(dw,e[1],ib.serialize(r))}else{const t=new mw(e[0]);super(dw,e[1],ib.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=ib.parse(e.extnValue,mw);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map(e=>new BB(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}qB.NAME="CRL Distribution Points";class zB extends nB{constructor(...e){var t,r,s,i;if(Hf.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Gv){const t=new Gv(e[0]);super(Qv,e[1],ib.serialize(t))}else{const t=e[0],r=new Gv;JB(r,t,Mv,"ocsp"),JB(r,t,Pv,"caIssuers"),JB(r,t,Lv,"timeStamping"),JB(r,t,Hv,"caRepository"),super(Qv,e[1],ib.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(s=this.timeStamping)&&void 0!==s||(this.timeStamping=[]),null!==(i=this.caRepository)&&void 0!==i||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],ib.parse(e.extnValue,Gv).forEach(e=>{switch(e.accessMethod){case Mv:this.ocsp.push(new BB(e.accessLocation));break;case Pv:this.caIssuers.push(new BB(e.accessLocation));break;case Lv:this.timeStamping.push(new BB(e.accessLocation));break;case Hv:this.caRepository.push(new BB(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&WB(e,"OCSP",this.ocsp),this.caIssuers.length&&WB(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&WB(e,"Time Stamping",this.timeStamping),this.caRepository.length&&WB(e,"CA Repository",this.caRepository),e}}function WB(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new tB("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[tB.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function JB(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new BB("url",t)),e.push(new Fv({accessMethod:r,accessLocation:ib.parse(t.rawData,Uv)}))})}zB.NAME="Authority Info Access";class YB extends iB{constructor(...e){let t;if(Hf.isBufferSource(e[0]))t=Hf.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>Hf.toArrayBuffer(e)):[];t=ib.serialize(new Jw({type:r,values:s}))}super(t,Jw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new tB("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[tB.NAME]===YB.NAME&&(e[tB.NAME]=rB.toString(this.type)),e}}YB.NAME="Attribute";class XB extends YB{constructor(...e){var t;if(Hf.isBufferSource(e[0]))super(e[0]);else{const t=new lx({printableString:e[0]});super(Gk,[ib.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=ib.parse(this.values[0],lx);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[tB.VALUE]=this.password,e}}XB.NAME="Challenge Password";class ZB extends YB{constructor(...e){var t;if(Hf.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new gS;for(const e of t)r.push(ib.parse(e.rawData,dS));super($k,[ib.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=ib.parse(this.values[0],gS);this.items=e.map(e=>$B.create(ib.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[tB.NAME]]=r;return e}}ZB.NAME="Extensions";class e_{static register(e,t){this.items.set(e,t)}static create(e){const t=new YB(e),r=this.items.get(t.type);return r?new r(e):t}}e_.items=new Map;const t_="crypto.signatureFormatter";var r_;let s_=r_=class{static createPssParams(e,t){const r=r_.getHashAlgorithm(e);return r?new KC({hashAlgorithm:r,maskGenAlgorithm:new aS({algorithm:NC,parameters:ib.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=yk.resolve(Ix);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new aS({algorithm:yC,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new aS({algorithm:wC,parameters:null});case"sha-256":return new aS({algorithm:EC,parameters:null});case"sha-384":return new aS({algorithm:CC,parameters:null});case"sha-512":return new aS({algorithm:kC,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=r_.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new aS({algorithm:AC,parameters:ib.serialize(t)})}return new aS({algorithm:AC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case yC:return{name:"RSASSA-PKCS1-v1_5"};case wC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case EC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case CC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case kC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case AC:if(e.parameters){const t=ib.parse(e.parameters,KC);return{name:"RSA-PSS",hash:yk.resolve(Ix).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};s_=r_=nb([mk()],s_),yk.registerSingleton(Ax,s_);let i_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new aS({algorithm:_C});case"sha-256":return new aS({algorithm:OC});case"sha-384":return new aS({algorithm:UC});case"sha-512":return new aS({algorithm:TC})}return null}toWebAlgorithm(e){switch(e.algorithm){case _C:return{name:"SHA-1"};case OC:return{name:"SHA-256"};case UC:return{name:"SHA-384"};case TC:return{name:"SHA-512"}}return null}};i_=nb([mk()],i_),yk.registerSingleton(Ax,i_);class n_{addPadding(e,t){const r=Hf.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=Hf.toUint8Array(e);for(let e=0;e<r.length;e++)if(r[e]){r=r.slice(e);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,s=n_.namedCurveSize.get(r)||n_.defaultNamedCurveSize,i=new fC,n=Hf.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),ib.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=ib.parse(t,fC),s=e.namedCurve,i=n_.namedCurveSize.get(s)||n_.defaultNamedCurveSize;return qf(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}n_.namedCurveSize=new Map,n_.defaultNamedCurveSize=32;const o_="1.3.101.110",a_="1.3.101.111",c_="1.3.101.112",l_="1.3.101.113";let h_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=c_;break;case"x25519":t=o_;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=c_;break;case"ed448":t=l_}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=o_;break;case"x448":t=a_}}return t?new aS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case c_:return{name:"Ed25519"};case l_:return{name:"EdDSA",namedCurve:"Ed448"};case o_:return{name:"X25519"};case a_:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};h_=nb([mk()],h_),yk.registerSingleton(Ax,h_);(class extends DB{constructor(e){DB.isAsnEncoded(e)?super(e,bx):super(e),this.tag=NB.CertificateRequestTag}onInit(e){this.tbs=ib.serialize(e.certificationRequestInfo),this.publicKey=new MB(e.certificationRequestInfo.subjectPKInfo);const t=yk.resolve(Ix);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>e_.create(ib.serialize(e)));const r=this.getAttribute($k);this.extensions=[],r instanceof ZB&&(this.extensions=r.items),this.subjectName=new gB(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=cB.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=yk.resolveAll(t_).reverse();let i=null;for(const e of s)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,i,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=ib.parse(this.rawData,bx),r=t.certificationRequestInfo,s=new tB("",{Version:`${fS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new tB("");for(const t of this.attributes){const r=t.toTextObject();e[r[tB.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new tB("",{Algorithm:sB.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var u_;(class extends DB{constructor(e){DB.isAsnEncoded(e)?super(e,yS):super(e),this.tag=NB.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=ib.serialize(t),this.serialNumber=jf.ToHex(t.serialNumber),this.subjectName=new gB(t.subject),this.subject=new gB(t.subject).toString(),this.issuerName=new gB(t.issuer),this.issuer=this.issuerName.toString();const r=yk.resolve(Ix);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;const s=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!s)throw new Error("Cannot get 'notBefore' value");this.notBefore=s;const i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>$B.create(ib.serialize(e)))),this.publicKey=new MB(t.subjectPublicKeyInfo)}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>"string"==typeof e?t.type===e:t instanceof e)}async verify(e={},t=cB.get()){let r,s;const i=e.publicKey;try{if(i)if("publicKey"in i)r={...i.publicKey.algorithm,...this.signatureAlgorithm},s=await i.publicKey.export(r,["verify"],t);else if(i instanceof MB)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(Hf.isBufferSource(i)){const e=new MB(i);r={...e.algorithm,...this.signatureAlgorithm},s=await e.export(r,["verify"],t)}else r={...i.algorithm,...this.signatureAlgorithm},s=i;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],t)}catch(e){return!1}const n=yk.resolveAll(t_).reverse();let o=null;for(const e of n)if(o=e.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,s,o,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=cB.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=cB.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=ib.parse(this.rawData,yS),r=t.tbsCertificate,s=new tB("",{Version:`${fS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":sB.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new tB("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(s["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(s["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new tB("");for(const t of this.extensions){const r=t.toTextObject();e[r[tB.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new tB("",{Algorithm:sB.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}).NAME="Certificate",function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(u_||(u_={})),$B.register(zv,LB),$B.register(Ew,VB),$B.register(Mw,QB),$B.register(Zw,FB),$B.register($v,PB),$B.register(zw,GB),$B.register(dw,qB),$B.register(Qv,zB),e_.register(Gk,XB),e_.register($k,ZB),yk.registerSingleton(t_,class{toAsnSignature(e,t){return Hf.toArrayBuffer(t)}toWebSignature(e,t){return Hf.toArrayBuffer(t)}}),yk.registerSingleton(t_,n_),n_.namedCurveSize.set("P-256",32),n_.namedCurveSize.set("K-256",32),n_.namedCurveSize.set("P-384",48),n_.namedCurveSize.set("P-521",66),Js.new(void 0,"networking");const d_=new class extends jA{constructor(){super(...arguments),this.subtle=new bv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=YA.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return ZA().randomFillSync(t),e}};var g_,f_,p_;function y_(e){return Z(e)}cB.set(d_),(p_=g_||(g_={}))[p_.NoCertificate=0]="NoCertificate",p_[p_.NotEd25519=1]="NotEd25519",p_[p_.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",p_[p_.AltNameMismatch=3]="AltNameMismatch",p_[p_.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(f_||(f_={})),Js.new(void 0,"net:peers"),Js.new(void 0,"net"),Js.new(void 0,"net"),Js.new(void 0,"net"),Js.new(void 0,"jamnps");const m_=y_(0);class b_ extends k{hash;slot;static Codec=ke.Class(b_,{hash:ke.bytes(Ne).asOpaque(),slot:ke.u32.asOpaque()});static create({hash:e,slot:t}){return new b_(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class A_{final;leafs;static Codec=ke.Class(A_,{final:b_.Codec,leafs:ke.sequenceVarLen(b_.Codec)});static create({final:e,leafs:t}){return new A_(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class I_ extends k{header;final;static Codec=ke.Class(I_,{header:Xr.Codec,final:b_.Codec});static create({header:e,final:t}){return new I_(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const v_=Js.new(void 0,"protocol/up-0");class w_{getHandshake;onAnnouncement;kind=m_;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t){this.getHandshake=e,this.onAnnouncement=t}onStreamMessage(e,t){const r=e.streamId;if(!this.handshakes.has(r)){const s=ue.decodeObject(A_.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(v_.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(me.encodeObject(A_.Codec,this.getHandshake()))))}const s=ue.decodeObject(I_.Codec,t);v_.info(`[${r}] got blocks announcement: ${s}`),this.onAnnouncement(s)}onClose(e){this.handshakes.delete(e)}sendHandshake(e,t){this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(me.encodeObject(A_.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(me.encodeObject(I_.Codec,t)):v_.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var S_;y_(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(S_||(S_={}));class E_ extends k{headerHash;direction;maxBlocks;static Codec=ke.Class(E_,{headerHash:ke.bytes(Ne).asOpaque(),direction:ke.u8.convert(e=>Z(e),e=>{switch(e){case S_.AscExcl:return S_.AscExcl;case S_.DescIncl:return S_.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:ke.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new E_(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}Js.new(void 0,"protocol/ce-128");const C_=y_(129),k_=ke.bytes(64).convert(e=>M.fromBlob(e.raw,64),e=>new tn(e.raw));class x_ extends k{key;value;static Codec=ke.Class(x_,{key:ke.bytes(Zi),value:ke.blob});static create({key:e,value:t}){return new x_(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class B_ extends k{keyValuePairs;static Codec=ke.Class(B_,{keyValuePairs:ke.sequenceVarLen(x_.Codec)});static create({keyValuePairs:e}){return new B_(e)}constructor(e){super(),this.keyValuePairs=e}}class __ extends k{headerHash;startKey;endKey;maximumSize;static Codec=ke.Class(__,{headerHash:ke.bytes(Ne).asOpaque(),startKey:ke.bytes(Zi),endKey:ke.bytes(Zi),maximumSize:ke.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new __(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const R_=Js.new(void 0,"protocol/ce-129");class O_{isServer;getBoundaryNodes;getKeyValuePairs;kind=C_;boundaryNodes=new Map;onResponse=new Map;constructor(e=!1,t,r){if(this.isServer=e,this.getBoundaryNodes=t,this.getKeyValuePairs=r,e&&(void 0===t||void 0===r))throw new Error("getBoundaryNodes and getKeyValuePairs are required in server mode.")}onStreamMessage(e,t){if(this.isServer){if(R_.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=ue.decodeObject(__.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return R_.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(me.encodeObject(ke.sequenceVarLen(k_),s)),e.bufferAndSend(me.encodeObject(B_.Codec,B_.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,ue.decodeObject(ke.sequenceVarLen(k_),t)),void R_.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(ue.decodeObject(B_.Codec,t)),R_.info(`[${e.streamId}][client]: Received state values.`)}onClose(e){this.boundaryNodes.delete(e),this.onResponse.delete(e)}getStateByKey(e,t,r,s){if(this.onResponse.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");this.onResponse.set(e.streamId,s),e.bufferAndSend(me.encodeObject(__.Codec,__.create({headerHash:t,startKey:r,endKey:r,maximumSize:se(4096)}))),e.close()}}y_(131),y_(132);class U_ extends k{epochIndex;ticket;static Codec=ke.Class(U_,{epochIndex:ke.u32.asOpaque(),ticket:xt.Codec});static create({epochIndex:e,ticket:t}){return new U_(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}Js.new(void 0,"protocol/ce-131-ce-132"),y_(133);class T_ extends k{coreIndex;workPackage;static Codec=ke.Class(T_,{coreIndex:ke.u16.asOpaque(),workPackage:Mr.Codec});static create({coreIndex:e,workPackage:t}){return new T_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}Js.new(void 0,"protocol/ce-133"),ke.blob,y_(134);class N_ extends k{coreIndex;segmentsRootMappings;static Codec=ke.Class(N_,{coreIndex:ke.u16.asOpaque(),segmentsRootMappings:ke.sequenceVarLen(Fr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new N_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class D_ extends k{workReportHash;signature;static Codec=ke.Class(D_,{workReportHash:ke.bytes(Ne).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,signature:t}){return new D_(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}Js.new(void 0,"protocol/ce-134"),y_(135);class M_ extends k{report;slot;signatures;static Codec=ke.Class(M_,{report:Gr.Codec,slot:ke.u32.asOpaque(),signatures:St(e=>Et(jr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new M_(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}Js.new(void 0,"protocol/ce-135");const P_=t(import.meta.url)("node:net"),L_=t(import.meta.url)("node:path"),H_=t(import.meta.url)("node:buffer");var K_;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(K_||(K_={}));class V_{streamId;type;data;static Codec=ke.Class(V_,{streamId:ke.u32,type:ke.u8.convert(e=>Z(e),e=>{switch(e){case K_.Msg:return K_.Msg;case K_.Open:return K_.Open;case K_.Close:return K_.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:ke.blob});static create({streamId:e,type:t,data:r}){return new V_(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class Q_{streamByte;static Codec=ke.Class(Q_,{streamByte:ke.u8});static create({streamByte:e}){return new Q_(e)}constructor(e){this.streamByte=e}}const F_=Js.new(void 0,"ext-ipc");class G_{streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;sender;constructor(e){const t={finished:!1};t.listen=new Promise((e,r)=>{t.resolve=e,t.reject=r}),this.onEnd=t,this.sender=new j_(e)}registerHandlers(...e){for(const t of e)this.streamHandlers.set(t.kind,t)}withStreamOfKind(e,t){for(const[r,s]of this.streams.entries())if(s.kind===e)return void t(s,new $_(r,this.sender));throw new Error(`Missing handler for ${e}!`)}withNewStream(e,t){const r=this.streamHandlers.get(e);if(void 0===r)throw new Error(`Stream with unregistered handler of kind: ${e} was requested to be opened.`);const s=this.streams,i=function e(){const t=Math.floor(65536*Math.random());return s.has(t)?e():t}();this.streams.set(i,r),this.pendingStreams.set(i,!0);const n=new $_(i,this.sender);n.open(Q_.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=ue.decodeObject(V_.Codec,e),r=t.streamId;F_.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new $_(r,this.sender);if(void 0===s){if(t.type!==K_.Open)return void F_.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=ue.decodeObject(Q_.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(F_.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===K_.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===K_.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||F_.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){F_.log(`Closing the handler. Reason: ${void 0!==e?e.message:"close"}.`);for(const[t,r]of this.streams.entries())r.onClose(t,void 0===e);this.streams.clear(),this.onEnd.finished=!0,void 0!==e?this.onEnd.reject(e):this.onEnd.resolve()}waitForEnd(){return F_.log("Waiting for the handler to be closed."),this.onEnd.listen}}class $_{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=me.encodeObject(Q_.Codec,e);this.sender.send(me.encodeObject(V_.Codec,V_.create({streamId:this.streamId,type:K_.Open,data:t})))}bufferAndSend(e){return this.sender.send(me.encodeObject(V_.Codec,V_.create({streamId:this.streamId,type:K_.Msg,data:e}))),!0}close(){this.sender.send(me.encodeObject(V_.Codec,V_.create({streamId:this.streamId,type:K_.Close,data:D.blobFromNumbers([])})))}}class j_{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(q_);me.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const q_=4;function z_(e){const t=function(e){const t=new En.EventEmitter;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=b_.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",I_.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===Ts.platform()?"\\\\.\\pipe\\typeberry":L_.join(Ts.tmpdir(),"typeberry.ipc"),n=Js.new(void 0,"ext-ipc"),o=(0,P_.createServer)(i=>{n.log("Client connected");const o=new G_(i);o.registerHandlers(new w_(t,()=>{})),o.registerHandlers(new O_(!0,r,s));const a=e=>{if(!(e instanceof I_))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(m_,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=H_.Buffer.alloc(0),r=-1;return s=>{t=H_.Buffer.concat([t,s]);do{if(-1===r){if(t.length<q_)break;r=t.readUint32LE(),t=t.subarray(q_)}if(t.length<r)break;const s=t.subarray(0,r);t=t.subarray(r),r=-1,e(s)}while(t.length>0)}}(e=>{try{o.onSocketMessage(new Uint8Array(e))}catch(e){n.error(`Received invalid data on socket: ${e}. Closing connection.`),i.end()}})),i.on("end",()=>{n.log("Client disconnected"),o.onClose({}),e.off("annoucement",a)}),i.on("error",e=>{n.error(`Socket error: ${e}`),o.onClose({error:e}),i.end()})});try{Os.unlinkSync(i)}catch{}const a=new AbortController;return o.listen({path:i,signal:a.signal},()=>{n.log(`IPC server is listening at ${i}`)}),o.on("error",e=>{throw e}),()=>{n.info("Closing IPC server."),o.close(),a.abort(),o.unref()}}(t,()=>{const e=r??b_.create({hash:M.zero(Ne).asOpaque(),slot:Ar(0)});return A_.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=D.blobFromNumbers([255,255,0,0]);return M.fromBlob($e("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,De),De).isEqualTo(t)&&(r=D.blobFromNumbers([255,255,255,0])),[new x_(t,r)]})}(e);return()=>{t()}}const W_=e=>e.endsWith(".json");function J_(e,t){const r=Us().readFileSync(e),s=D.blobFrom(new Uint8Array(r));return ue.decodeObject(is.Codec.View,s,t)}function Y_(e,t){const r=Us().readFileSync(e,"utf-8"),s=J(JSON.parse(r),(i=t,X.object({header:Bs,extrinsic:(n=i,X.object({tickets:Ss,preimages:vs,guarantees:As,assurances:gr(n),disputes:ls},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>ss.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>is.create({header:e,extrinsic:t}))));var i,n;const o=me.encodeObject(is.Codec,s,t);return ue.decodeObject(is.Codec.View,o,t)}const X_={genesisPath:"",timeSlot:Ar(0),validatorIndex:Ir(0)};class Z_{isAuthoring;blocksToImport;nodeName;node;dev;static new({isAuthoring:e,blockToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n}){let o=i??{...X_};return void 0!==n&&(o={...o,...n}),new Z_(e??!1,t??[],r,s,o)}constructor(e,t,r,s,i){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i}}const eR=Js.new(void 0,"jam");var tR;async function rR(e,t){if(!Ys.isMainThread)return void eR.error("The main binary cannot be running as a Worker!");const r=nR(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=$e(e).toString().substring(2,10),n=Ge(t).asOpaque(),o=`${r}/${i}/${n.toString().substring(2,10)}`;eR.info(`🛢️ Opening database at ${o}`);try{return{dbPath:o,rootDb:new si(o,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${o}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new Zs(e,r),n=new Sn(e,r),o=i.getBestHeaderHash(),a=i.getPostStateRoot(o);if(eR.log(`🛢️ Best header hash: ${o}`),eR.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(M.zero(Ne))&&!o.isEqualTo(M.zero(Ne)))return void await r.db.close();eR.log("🛢️ Database looks fresh. Initializing.");const c=ue.decodeObject(Xr.Codec,s.genesisHeader,e),l=is.create({header:Xr.empty(),extrinsic:ss.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,h=is.create({header:c,extrinsic:l}),u=ue.decodeObject(is.Codec.View,me.encodeObject(is.Codec,h,e),e);eR.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:d,genesisStateRootHash:g}=function(e,t){const r=bt.fromEntries(Array.from(t.entries())),s=gn.fromTruncatedDictionaryUnsafe(r),i=Yi.fromStateEntries(e,s),n=s.getRootHash();return eR.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new Me(t,u)),await n.insertState(t,d),await i.setPostStateRoot(t,g),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const o=await async function(){const e=xh,t=new Ch;return Vn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),a=z_({bestHeader:o.getState("ready(main)").onBestBlock}),c=new wt(r,i,e.node.authorship.omitSealVerification),l=o.transition((e,t)=>e.sendConfig(t,c)),h=iR(l,r,e.blocksToImport),u=await sR(e.isAuthoring,c,l);eR.info("[main]⌛ waiting for importer to finish");const d=await h;eR.log("[main] ☠️ Closing the extensions"),a(),eR.log("[main]⌛ waiting for tasks to finish"),await d.currentState().waitForWorkerToFinish(),eR.log("[main] ☠️ Closing the authorship module"),u(),eR.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(tR||(tR={}));const sR=async(e,t,r)=>{if(!e)return()=>Promise.resolve();eR.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=Nh,t=new Uh;return Vn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/block-generator/index.ts"),e,"ready(main)",t)}()).transition((t,r)=>t.sendConfig(r,e));return{generator:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(t);return r.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{eR.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},iR=async(e,t,r)=>null===r?e.waitForState("finished"):(eR.info(`📖 Reading ${r.length} blocks`),e.transition((e,s)=>{const i=function*(e){const{chainSpec:t}=e;for(const r of e.files){const e=W_(r)?Y_(r,t):J_(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)eR.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return eR.info("All blocks scheduled to be imported."),e.finish(s)})),nR=e=>{if(e===Hs.Full)return vt;if(e===Hs.Tiny)return It;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[Hs.Full,Hs.Tiny]}`)},oR=(e=>{var t={};return o.d(t,e),t})({default:()=>s.default}),aR=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${Ls.name}]\n --config Path to a config file or '${Ps}'.\n [default: ${Ls.config}]\n`;var cR;function lR(e,t){const{name:r}=uR(e,"name",e=>e,Ls.name),{config:s}=uR(e,"config",e=>e===Ps?Ps:t(e),Ls.config);return{nodeName:r,configPath:s}}function hR(e,t){const r=(0,oR.default)(e),s=r._.shift()??cR.Run;switch(s){case cR.Run:{const e=lR(r,t);return dR(r),{command:cR.Run,args:e}}case cR.Import:{const e=lR(r,t),s=r._.map(e=>t(e));return r._=[],dR(r),{command:cR.Import,args:{...e,files:s}}}default:r._.unshift(s),dR(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function uR(e,t,r,s){const i=e[t];if(void 0===i)return{[t]:s};if(delete e[t],"string"!=typeof i)throw new Error(`Option '--${t}' requires an argument.`);try{const e=r(i);return{[t]:e??s}}catch(e){throw new Error(`Invalid value '${i}' for option '${t}': ${e}`)}}function dR(e){const t=Object.keys(e).filter(e=>"_"!==e&&"--"!==e);if(e._.length>0)throw new Error(`Unexpected command: '${e._[0]}'`);if((e["--"]?.length??0)>0)throw new Error(`Unexpected parameters: '${e["--"]?.[0]}'...`);if(t.length>0)throw new Error(`Unrecognized options: '${t}'`)}!function(e){e.Run="run",e.Import="import"}(cR||(cR={}));const gR=e=>{const t=e.command===cR.Import?e.args.files:[],r=function(e){if(e===Ps)return J(Ds,Vs.fromJson);try{const t=Us().readFileSync(e,"utf8");return J(JSON.parse(t),Vs.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath);return Z_.new({isAuthoring:!1,blockToImport:t,nodeName:e.args.nodeName,nodeConfig:r})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,c.pathToFileURL)(process.argv[1]).href){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=hR(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(aR),process.exit(1)}rR(gR(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let fR;Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);try{fR=hR(process.argv.slice(2),pR)}catch(e){console.error(`\n${e}\n`),console.info(aR),process.exit(1)}function pR(e){return e}rR(gR(fR),pR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{cR as Command,aR as HELP,hR as parseArgs,gR as prepareConfigFile};
3
3
  //# sourceMappingURL=typeberry.mjs.map