@typeberry/jam 0.0.1-83eaca5 → 0.0.1-866dcf0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- 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),a=r(8),o=r(8),c=r(8),l=r(154),d=r(984),u=r(872),h=r(984);class f{getValue(){return this.value}toBinaryString(){return o.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=f;class g extends f{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 g(e)}static fromDecimalDottedString(e){return new g(e)}static fromString(e){return g.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(a.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return g.fromNumber(this.getValue()+1n)}previousIPNumber(){return g.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return b.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[a,o]=i.Validator.isValidIPv4String(e);if(!a)throw new Error(o.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=o.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(a.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=g;class p extends f{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 b extends f{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 b(e)}static fromHexadecatet(e){return new b(e)}static fromString(e){return b.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=o.leftPadWithZeroBit(e,128);return new b(a.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new g(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 b.fromBigInt(this.getValue()+1n)}previousIPNumber(){return b.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${h.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=d.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=b;class m extends g{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 a=e.split(".");this.octets=a.map(e=>s.Octet.fromString(e));let o=n.dottedDecimalNotationToBinaryString(e);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class y extends b{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 a=h.hexadectetNotationToBinaryString(s);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`),this.value=BigInt(`0b${h.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new y(e)}}t.IPv6Mask=y,t.isIPv4=function(e){return 32===e.bitSize}},239:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,a=null;function o(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return o().set(e,r/1),c=e.length,r}let d=null;function u(){return null!==d&&0!==d.byteLength||(d=new Int32Array(n.memory.buffer)),d}function h(e,t){return e>>>=0,o().subarray(e/1,e/1+t)}t.exports.ring_commitment=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.ring_commitment(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.derive_public_key=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.derive_public_key(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.verify_seal=function(e,t,r,s,i){try{const f=n.__wbindgen_add_to_stack_pointer(-16),g=l(e,n.__wbindgen_malloc),p=c,b=l(r,n.__wbindgen_malloc),m=c,y=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(f,g,p,t,b,m,y,A,I,v);var a=u()[f/4+0],o=u()[f/4+1],d=h(a,o).slice();return n.__wbindgen_free(a,1*o,1),d}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.batch_verify_tickets=function(e,t,r){try{const o=n.__wbindgen_add_to_stack_pointer(-16),d=l(e,n.__wbindgen_malloc),f=c,g=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(o,d,f,g,p,r);var s=u()[o/4+0],i=u()[o/4+1],a=h(s,i).slice();return n.__wbindgen_free(s,1*i,1),a}finally{n.__wbindgen_add_to_stack_pointer(16)}};const f=s(928).join(i,"bandersnatch_bg.wasm"),g=s(896).readFileSync(f),p=new WebAssembly.Module(g),b=new WebAssembly.Instance(p,{});n=b.exports,t.exports.__wasm=n},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 a=e[t.charCodeAt(i++)],o=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=a<<2|o>>4,s[n++]=o<<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},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),a=r(660);class o{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 o(e,e)}static fromCidrRange(e){return new o(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]=a.Validator.isValidIPv4String(r),[c]=a.Validator.isValidIPv4String(i),[l]=a.Validator.isValidIPv6String(r),[d]=a.Validator.isValidIPv6String(i);if(n&&c)return new o(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&d)return new o(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 o(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new o(this.getFirst(),e.getLast()):new o(e.getFirst(),this.getLast());if(this.contains(e))return new o(this.getFirst(),this.getLast());if(e.contains(this))return new o(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 o(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new o(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 o(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),a=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new o(i,a)}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 o(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new o(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 d(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=o;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 o(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]=a.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(o),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=a.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 d extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=a.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new d(s.IPv6.fromHexadecatet(o),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 d(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 d(r,t),n=s.getLast().nextIPNumber();return[s,new d(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 d(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 d(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new d(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=d;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),a=e.cidrPrefix.toMask().getValue(),o=n.leftPadWithZeroBit((a^i).toString(2),r);return h(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(o)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(o))};function h(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=h},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},493:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmF3YWl0IHRzSW1wb3J0KCIuL2luZGV4LnRzIiwgaW1wb3J0Lm1ldGEudXJsKTsK"},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),a=r(984),o=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-d(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-d(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=>o.Hexadecatet.fromString(a.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function d(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,a="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),o=64,c=[];e.exports=p;var l=e.exports.BYTES_MIN=16,d=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),h=e.exports.KEYBYTES_MAX=64,f=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),g=e.exports.PERSONALBYTES=16;function p(e,t,r,i,a){if(!(this instanceof p))return new p(e,t,r,i,a);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==a&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=d,"digestLength must be at most "+d+", 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<=h,"key must be at least "+h+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===f,"salt must be exactly "+f+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===g,"personal must be exactly "+g+", was given "+i.length))),c.length||(c.push(o),o+=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,o,o+t.length),this._memory[this.pointer+200]=128)}function b(){}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"),o+e.length>this._memory.length&&this._realloc(o+e.length),this._memory.set(e,o),n.blake2b_update(this.pointer,o,o+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=b),a?a.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,a={};a.__wbindgen_placeholder__=t.exports;let o=null;function c(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let l=0;function d(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=d(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,a,o=(i=s[0],a=s[1],i>>>=0,c().subarray(i/1,i/1+a)).slice();return n.__wbindgen_free(s[0],1*s[1],1),o},t.exports.verify_ed25519_batch=function(e){const t=d(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"),h=s(896).readFileSync(u),f=new WebAssembly.Module(h),g=new WebAssembly.Instance(f,a);n=g.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),a=r(984),o=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=o.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),[a,o]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&a,d=n.concat(o);return l?[l,[]]:[l,d]}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,a.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("/"),a=n[0],o=n[1],l=BigInt(`0b${r(a)}`),d=(l&BigInt(`0b${s(parseInt(o))}`))===l;return d?[d,[]]:[d,[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${o.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${o.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],[a,o]=t(i),[l,d]=t(n),u=a&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let h=o.concat(d);return u?[u,[]]:[u,h]}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 a(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 o(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,o){var c=h[i],l=h[i+1],d=h[o],f=h[o+1];n(u,e,t),a(u,e,c,l);var g=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=g,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=g>>>24^p<<8,u[t+1]=p>>>24^g<<8,n(u,e,t),a(u,e,d,f),g=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=g>>>16^p<<16,u[s+1]=p>>>16^g<<16,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^g<<1,u[t+1]=g>>>31^p<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),d=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),h=new Uint32Array(32);function f(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++)h[r]=o(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,d[16*r+0],d[16*r+1]),c(2,10,18,26,d[16*r+2],d[16*r+3]),c(4,12,20,28,d[16*r+4],d[16*r+5]),c(6,14,22,30,d[16*r+6],d[16*r+7]),c(0,10,20,30,d[16*r+8],d[16*r+9]),c(2,12,22,24,d[16*r+10],d[16*r+11]),c(4,14,16,26,d[16*r+12],d[16*r+13]),c(6,8,18,28,d[16*r+14],d[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var g=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){g.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,g[0]=e,t&&(g[1]=t.length),g[2]=1,g[3]=1,r&&g.set(r,32),s&&g.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^o(g,4*i);t&&(b(this,t),this.c=128)}function b(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,f(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"),b(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;f(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 y=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 y(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],a=i.split(":").filter(e=>""!==e),o=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(a.length+o.length)),l=t(a);""!==l&&(l+=":");let d=t(o);return""!==d&&(d=":"+d),`${l}${c}${d}${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",a="function"==typeof Object.create,o={__proto__:[]}instanceof Array,c=!a&&!o,l={create:a?function(){return Q(Object.create(null))}:o?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]}},d=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,a)},t.prototype.entries=function(){return new r(this._keys,this._values,o)},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 a(e,t){return t}function o(e,t){return[e,t]}}(),h="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}(),f="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@@"+a()}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 a(){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}}(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[g]),C(e)&&(e=function(){var e,r,s,i;C(g)||void 0===t.Reflect||g 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,a=new f,o={isProviderFor:function(e,t){var r=a.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return o}(t.Reflect));var n=new f,a={registerProvider:o,getProvider:l,setProvider:p};return a;function o(t){if(!Object.isExtensible(a))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 h),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 a=M(i);;){var o=L(a);if(!o)return;var c=P(o);if(c.isProviderFor(t,n))return H(a),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 d(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function p(e,t,r){if(!d(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(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),b=function(e){var t=new f,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)&&B(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()),a=0;;){var o=L(n);if(!o)return r.length=a,r;var c=P(o);try{r[a]=c}catch(e){try{H(n)}finally{throw e}}a++}},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 a=t.get(r);C(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}};return p.registerProvider(r),r;function s(s,i,n){var a=t.get(s),o=!1;if(C(a)){if(!n)return;a=new u,t.set(s,a),o=!0}var c=a.get(i);if(C(c)){if(!n)return;if(c=new u,a.set(i,c),!e.setProvider(s,i,r))throw a.delete(i),o&&t.delete(s),new Error("Wrong provider for target.")}return c}}(p);function m(e,t,r){if(y(e,t,r))return!0;var s=V(t);return!k(s)&&m(e,s,r)}function y(e,t,r){var s=K(t,r,!1);return!C(s)&&B(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(y(e,t,r))return I(e,t,r);var s=V(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=K(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){K(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=V(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 h,a=[],o=0,c=r;o<c.length;o++){var l=c[o];n.has(l)||(n.add(l),a.push(l))}for(var d=0,u=i;d<u.length;d++)l=u[d],n.has(l)||(n.add(l),a.push(l));return a}function S(e,t){var r=K(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 _(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 B(e){return!!e}function R(e){var t=_(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 V(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===d)return t;if(t!==d)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 K(e,t,r){var s=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.setProvider(e,t,b))return b;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)),y(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=K(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 a,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 a=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,a,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 a{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 a(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 a(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 a(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 a(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,a),r.exports}a.m=i,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.b=new URL("./",import.meta.url);var o={};a.r(o),a.d(o,{Any:()=>Vd,BaseBlock:()=>el,BaseStringBlock:()=>rl,BitString:()=>ed,BmpString:()=>vd,Boolean:()=>Jl,CharacterString:()=>Ud,Choice:()=>Kd,Constructed:()=>Gl,DATE:()=>Dd,DateTime:()=>Pd,Duration:()=>Ld,EndOfContent:()=>ql,Enumerated:()=>ad,GeneralString:()=>Od,GeneralizedTime:()=>Nd,GraphicString:()=>Bd,HexBlock:()=>zc,IA5String:()=>_d,Integer:()=>nd,Null:()=>zl,NumericString:()=>Ed,ObjectIdentifier:()=>ld,OctetString:()=>Xl,Primitive:()=>Vl,PrintableString:()=>Cd,RawData:()=>Fd,RelativeObjectIdentifier:()=>hd,Repeated:()=>Qd,Sequence:()=>fd,Set:()=>gd,TIME:()=>Hd,TeletexString:()=>kd,TimeOfDay:()=>Md,UTCTime:()=>Td,UniversalString:()=>Sd,Utf8String:()=>Ad,ValueBlock:()=>Jc,VideotexString:()=>xd,ViewWriter:()=>Bc,VisibleString:()=>Rd,compareSchema:()=>$d,fromBER:()=>Ql,verifySchema:()=>Gd});var c={};a.r(c),a.d(c,{Announcement:()=>NS,Handler:()=>MS,Handshake:()=>TS,HashAndSlot:()=>US,STREAM_KIND:()=>OS});var l={};a.r(l),a.d(l,{Handler:()=>zS,KeyValuePair:()=>$S,STREAM_KIND:()=>QS,StateRequest:()=>jS,StateResponse:()=>GS});const d=t(import.meta.url)("node:url");var u,h,f;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(u||(u={}));class g{value;constructor(e){this.value=e}static Less=new g(u.Less);static Greater=new g(u.Greater);static Equal=new g(u.Equal);isLess(){return this.value===u.Less}isGreater(){return this.value===u.Greater}isEqual(){return this.value===u.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",e.V0_7_1="0.7.1"}(h||(h={})),function(e){e.W3F_DAVXY="w3f-davxy",e.W3F="w3f",e.JAMDUNA="jamduna",e.JAVAJAM="javajam"}(f||(f={}));const p=f.W3F,b=[h.V0_6_4,h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0,h.V0_7_1],m="undefined"==typeof process?{}:process.env,y=h.V0_6_7;let A=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: ${b}`);return t}(m.GP_VERSION),I=m.TEST_SUITE??p;class v{static override(e){A=e}static overrideSuite(e){I=e}static is(...e){return void 0===A?e.includes(y):e.includes(A)}static isSuite(e,t){if(void 0===I)return!1;const r=void 0===t||v.is(t);return e===I&&r}static isGreaterOrEqual(e){const t=b.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${b}`);return v.is(...b.slice(t))}static isLessThan(e){return!v.isGreaterOrEqual(e)}static selectIfGreaterOrEqual({fallback:e,versions:t}){for(const e of b.toReversed()){const r=t[e];if(void 0!==r&&v.isGreaterOrEqual(e))return r}return e}}function w(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function S(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function E(e){throw new Error(`Unexpected value: ${e}`)}function C(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function k(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=>k(e))}]`;if(e instanceof Map)return k(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&&_.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(k(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const x="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 _{toString(){return k(this)}}function B(e){return e}function R(e){return e}const O=Symbol("ok");class U{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}) - ${T(this.error)}`}}const T=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof U?e.toString():`${e.kind} - ${T(e.error)}`:`${e}`;var t};function N(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${T(e.error)}`}const D={ok:e=>(w(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(w(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>D.error(new U(t,r.error,e),r.details)},M=(t(import.meta.url)("node:assert"),Symbol("compare using"));class P{[M](){return this.toString()}raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=j?String.fromCharCode(e+Q-j):String.fromCharCode(e+V);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&&z(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 g.Less;if(r[e]>s[e])return g.Greater}return this.length<e.length?g.Less:this.length>e.length?g.Greater:g.Equal}static empty(){return new P(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return P.blobFrom(t.encode(e))}static blobFrom(e){return new P(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 P(i)}static blobFromNumbers(e){w(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new P(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]=H(t)}return new P(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return P.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield P.blobFrom(this.raw.subarray(t,t+e))}}class L extends P{length;constructor(e,t){super(e),w(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new L(e,t)}static fromNumbers(e,t){w(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new L(r,t)}static zero(e){return new L(new Uint8Array(e),e)}static fill(e,t){w((255&t)===t,"Input has to be a byte.");const r=L.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=P.parseBlobNoPrefix(e);return new L(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=P.parseBlob(e);return new L(r.raw,t)}isEqualTo(e){return w(this.length===e.length,"Comparing incorrectly typed bytes!"),z(this.raw,e.raw)}asOpaque(){return this}}function H(e){return w(2===e.length,"Two-character string expected"),q(e.charCodeAt(0))<<4|q(e.charCodeAt(1))}const V="0".charCodeAt(0),K="9".charCodeAt(0),Q="a".charCodeAt(0),F="f".charCodeAt(0),$="A".charCodeAt(0),G="F".charCodeAt(0),j=10;function q(e){if(e>=V&&e<=K)return e-V;if(e>=Q&&e<=F)return e-Q+j;if(e>=$&&e<=G)return e-$+j;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function z(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const W=(e,t)=>e.compare(t);class J{data;bitLength;static fromBlob(e,t){return new J(e,t)}static fromBytes(e,t){return new J(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new J(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,w(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){w(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){w(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){w(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 Y=Symbol("no key");function X(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]=X(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:X(e,t[1],r);if("object"===s)return Z(t[1],e,r);if("string"===s)return Z(t[1],X(e,s,r),r);if("number"===s){const s=t[0];return Z(t[1],X(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,a=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]=X(t,a[e],`${r}.${e}`)}else Array.isArray(a[e])&&"optional"===a[e][0]&&(i[e]=Y);const o=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 a=[],o=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&a.push(1===t?[o(e),o(void 0)]:[o(void 0),o(e)]);return a}(i,t);if(o.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${o.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===Y&&delete i[e];return i}function Z(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var ee;!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]=X(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,a]of Object.entries(r))i.set(X(n,e,`${s}.key`),X(a,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=X(r,e,s);return t(i)})}}(ee||(ee={}));const te=e=>S(e,re(e),`input must have one-byte representation, got ${e}`),re=e=>(255&e)===e,se=e=>S(e,ie(e),`input must have two-byte representation, got ${e}`),ie=e=>(65535&e)===e,ne=e=>S(e,ae(e),`input must have four-byte representation, got ${e}`),ae=e=>(4294967295&e)>>>0===e,oe=e=>{const t=BigInt(e);return S(t,ce(t),`input must have eight-byte representation, got ${e}`)},ce=e=>(18446744073709551615n&e)===e;function le(...e){let t=0n;for(const r of e)t+=r;const r=!ce(t);return t&=0xffffffffffffffffn,{overflow:r,value:oe(t)}}function de(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function ue(e){return w(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 fe{source;offset;context;static fromBytesBlob(e,t){return new fe(e.raw,t)}static fromBlob(e){return new fe(e)}static decodeObject(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.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 fe(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,L.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=pe(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=pe(e);if(this.offset+=1,0===t)return oe(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return oe(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 oe(r)}bytes(e){if(0===e)return L.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,L.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,P.blobFrom(t)}bitVecFixLen(e){if(0===e)return J.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 J.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):(w(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(w(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 ge=[255,254,252,248,240,224,192,128];function pe(e){w(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<ge.length;t++)if(e>=ge[t])return 8-t;return 0}function be(e){return w(e.isExact,"The value is not exact size estimation!"),e.bytes}function me(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const ye=10485760;class Ae{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new Ae(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(ye,t),{maxByteLength:ye}),s=new Uint8Array(r);return new Ae(s,r)}static encodeObject(e,t,r){const s=Ae.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 P.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;w(e<t,"Only for numbers up to 2**64 - 1"),w(-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(ne(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);w(e<r,`Only for numbers up to 2**${8*t} - 1`),w(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){w(e>=0,"Only for natural numbers."),w(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(ne(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(L.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(ne(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){w(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(ne(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}){w(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 Ie{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=pe(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 ve(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 we{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 Se{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 P.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return P.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];w(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 Ie(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 we(()=>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 S(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class Ee{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=S(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?P.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),P.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){w(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 Ie(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new we(()=>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 S(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Ce{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Ce(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Ce(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 Ie(e));const r=e.bytesRead();return P.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Ce(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 ke(e){return e.convert(e=>(w(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function xe(e){return{bytes:e,isExact:!0}}var _e,Be;function Re(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function Oe(e){return e.View!==e}(Be=_e||(_e={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Ce.new(`Bytes<${t}>`,xe(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),Be.varU32=Ce.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),Be.varU64=Ce.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),Be.u64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),Be.bytes(8)),Be.u32=Ce.withView("u32",xe(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),Be.bytes(4)),Be.u24=Ce.withView("u24",xe(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),Be.bytes(3)),Be.u16=Ce.withView("u16",xe(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),Be.bytes(2)),Be.u8=Ce.new("u8",xe(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),Be.i64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),Be.bytes(8)),Be.i32=Ce.withView("i32",xe(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),Be.bytes(4)),Be.i24=Ce.withView("i24",xe(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),Be.bytes(3)),Be.i16=Ce.withView("i16",xe(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),Be.bytes(2)),Be.i8=Ce.new("i8",xe(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),Be.bool=Ce.new("bool",xe(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),Be.blob=Ce.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),Be.string=Ce.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(P.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),Be.blob),Be.bitVecVarLen=Ce.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),Be.bitVecFixLen=e=>Ce.new(`BitVec[${e}]`,xe(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),Be.optional=e=>{const t=Ce.new(`Optional<${e.name}>`,me({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Oe(e)?Ce.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,Be.optional(e.View)):t},Be.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Ce.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{ve(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return ve(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return ve(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 ve(t,s,i),r.sequenceFixLen(e,s)};return Ce.new(i,r,(e,r)=>{ve(t,r.length,i);const s=r.encoded();e.bytes(L.fromBlob(s.raw,s.length))},t=>{const r=new Ee(t.clone(),e);return n(new Ie(t)),r},n)}(e,t))},Be.sequenceFixLen=(e,t)=>Ce.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 Ce.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},r=>{const i=new Ee(r.clone(),e,t);return s(new Ie(r)),i},s)}(e,{fixedLength:t})),Be.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Ce.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*me(e.sizeHint,t.sizeHint).bytes:32*(me(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const a=Array.from(n.entries());a.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(ne(a.length));for(const[r,s]of a)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,a=s??i.varU32();let o=null;for(let s=0;s<a;s+=1){const s=e.decode(i),a=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==o&&r(o,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${s}"!`);n.set(s,a),o=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return Oe(t)?Ce.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,Be.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},Be.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Ce.new(e,t,r,s,i),Be.select=({name:e,sizeHint:t},r)=>Ce.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),Be.object=(e,t="object",r=e=>e)=>Be.Class({name:t,create:r},e),Be.Class=(e,t)=>{let r=xe(0);Re(t,(e,t)=>{r=me(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Re(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Se{constructor(r){super(r,e,t)}}return Re(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Ce.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new Ie(e)),t},s)}(e,t,r,s);return Ce.withView(e.name,r,(e,r)=>{Re(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Re(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Ue=a(239);const Te=32,Ne=96,De=144,Me=144,Pe=32,Le=31;class He extends _{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ve extends He{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Ke{emptyHash(){return L.zero(Pe)}}const Qe=new Ke;var Fe,$e=a(675),Ge=a.n($e);function je(e,t=Qe){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Ge()(Pe);for(const t of e)s?.update(t instanceof P?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function qe(e,t=Qe){const r=Ge()(Pe),s=e instanceof P?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function ze(e,t=Qe){return qe(P.blobFromString(e),t)}function We(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Je{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 We(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Ye="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Xe=null!==(Fe=Ye.Buffer)&&void 0!==Fe?Fe:null,Ze=Ye.TextEncoder?new Ye.TextEncoder:null;function et(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const tt="a".charCodeAt(0)-10,rt="0".charCodeAt(0);function st(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+tt:r+rt,r=15&t[i],e[s++]=r>9?r+tt:r+rt}return String.fromCharCode.apply(null,e)}const it=null!==Xe?e=>{if("string"==typeof e){const t=Xe.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Xe.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 Ze.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},nt=new Uint8Array(256);for(let e=0;e<64;e++)nt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function at(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=nt[e.charCodeAt(t)],n=nt[e.charCodeAt(t+1)],a=nt[e.charCodeAt(t+2)],o=nt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|a>>2,i+=1,s[i]=(3&a)<<6|63&o,i+=1}return s}const ot=16384,ct=new Je,lt=new Map;function dt(e,t){return We(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),a=ct.dispatch(()=>We(this,void 0,void 0,function*(){if(!lt.has(e.name)){const t=at(e.data),r=WebAssembly.compile(t);lt.set(e.name,r)}const t=yield lt.get(e.name);r=yield WebAssembly.instantiate(t,{})})),o=(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+ot);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(it(e))},l=new Uint8Array(2*t),d=(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):st(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<ot;let h=u;switch(e.name){case"argon2":case"scrypt":h=()=>!0;break;case"blake2b":case"blake2s":h=(e,t)=>t<=512&&u(e);break;case"blake3":h=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":h=()=>!1}return yield(()=>We(this,void 0,void 0,function*(){r||(yield a);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,ot)}))(),{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:o,update:c,digest:d,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),a=r.exports.memory.buffer,o=new Uint8Array(a,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]=et(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(o,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),a=n(),o=4+a,c=r.exports.memory.buffer;if(t.length!==o)throw new Error(`Bad state length (expected ${o} 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]!==et(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,a).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!h(e,i))return o(i),c(e),d("hex",n);const a=it(e);return s.set(a),r.exports.Hash_Calculate(a.length,i,n),st(l,s,t)},hashLength:t}})}new Je,new Je,new DataView(new ArrayBuffer(4)),new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Je,new Je;var ut={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 ht(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Je,new Je;class ft{hasher;static async create(){return new ft(await function(e=512){if(ht(e))return Promise.reject(ht(e));const t=e/8;return dt(ut,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 gt(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return L.fromBlob(e.hasher.digest("binary"),Pe)}class pt{map=new Map;constructor(){}static new(){return new pt}static fromEntries(e){const t=new pt;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 bt{map;static viewDictionaryKeys(e){return new bt(e)}static from(e){const t=bt.new();return t.insertAll(e),t}static new(){return new bt}constructor(e=pt.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 mt(e){return e}class yt extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){w(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new yt(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 yt.new(r,t)}toString(){return k(Array.from(this))}}class At{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new At(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new At([],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 At(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,a=r(t[n],e);if(a.isEqual())return{idx:n,isEqual:!0};a.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){w(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,a=n.length,o=new Array(i+a);let c=0,l=0,d=0;for(;c<i&&l<a;)r(s[c],n[l]).isLess()?o[d++]=s[c++]:(r(s[c],n[l]).isGreater()||(o[d++]=s[c++]),o[d++]=n[l++]);for(;c<i;)o[d++]=s[c++];for(;l<a;)o[d++]=n[l++];return At.fromSortedArray(r,o)}*[Symbol.iterator](){for(const e of this.array)yield e}}class It extends At{static fromArray(e,t=[]){if(0===t.length)return new It([],e);const r=t.toSorted((t,r)=>e(t,r).value),s=r.length,i=[r[0]];for(let t=1;t<s;t++)e(r[t-1],r[t]).isEqual()||i.push(r[t]);return new It(i,e)}static fromArrayUnique(e,t){const r=t.toSorted((t,r)=>e(t,r).value),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 It(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new It([],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 It(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){w(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return It.fromSortedArray(r,t.array);if(0===t.length)return It.fromSortedArray(r,e.array);const s=At.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,It.fromSortedArray(r,s)}}class vt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=L.zero(Pe).asOpaque();return r.raw.set(e.raw.subarray(0,Le)),[r,t]});return new vt(pt.fromEntries(t))}truncatedKey=L.zero(Pe).asOpaque();constructor(e){this.dict=e}[M](){return this.dict}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.has(this.truncatedKey)}set(e,t){const r=L.zero(Pe);r.raw.set(e.raw.subarray(0,Le)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}*entries(){for(const[e,t]of this.dict.entries())yield[L.fromBlob(e.raw.subarray(0,Le),Le).asOpaque(),t]}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}class wt extends _{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;preimageExpungePeriod;slotDuration;epochLength;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;rotationPeriod;numberECPiecesPerSegment;erasureCodedPieceSize;maxBlockGas;maxRefineGas;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=se(Math.floor(e.validatorsCount/3)),this.validatorsSuperMajority=se(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,this.erasureCodedPieceSize=ne(4104/e.numberECPiecesPerSegment),this.maxBlockGas=e.maxBlockGas,this.maxRefineGas=e.maxRefineGas}}const St=new wt({validatorsCount:se(6),coresCount:se(2),epochLength:ne(12),contestLength:ne(10),maxTicketsPerExtrinsic:te(3),rotationPeriod:se(4),slotDuration:se(6),ticketsPerValidator:te(3),numberECPiecesPerSegment:ne(1026),preimageExpungePeriod:ne(v.isSuite(f.JAMDUNA)&&v.is(h.V0_6_4)?6:32),maxBlockGas:oe(2e7),maxRefineGas:oe(1e9)}),Et=new wt({validatorsCount:se(1023),coresCount:se(341),epochLength:ne(600),contestLength:ne(500),maxTicketsPerExtrinsic:te(16),rotationPeriod:se(10),slotDuration:se(6),ticketsPerValidator:te(2),numberECPiecesPerSegment:ne(6),preimageExpungePeriod:ne(19200),maxBlockGas:oe(35e8),maxRefineGas:oe(5e9)});class Ct{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new Ct(new wt(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function kt(e){const t=Et,{name:r,sizeHint:s}=e(t),i=new Map;return _e.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof wt){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 xt=(e,t,r)=>"fixedLength"in t?ke(_e.sequenceFixLen(e,t.fixedLength)).convert(R,mt):ke(_e.sequenceVarLen(e,t)).convert(R,mt),_t=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return _e.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),yt.new(e,t)))},Bt=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Ce.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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=pt.new(),n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${n}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class Rt extends _{attempt;signature;static Codec=_e.Class(Rt,{attempt:_e.u8.asOpaque(),signature:_e.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new Rt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Ot extends _{id;attempt;static Codec=_e.Class(Ot,{id:_e.bytes(Pe),attempt:_e.u8.asOpaque()});static create({id:e,attempt:t}){return new Ot(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const Ut=xt(Rt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Tt;!function(e){e.bytesN=e=>ee.fromString(t=>L.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>ee.fromString(t=>L.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>ee.fromString(e=>L.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>ee.fromString(e=>L.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=ee.fromString(P.parseBlob),e.bytesBlobNoPrefix=ee.fromString(P.parseBlobNoPrefix),e.ed25519Signature=ee.fromString(e=>L.parseBytes(e,64).asOpaque()),e.ticketAttempt=ee.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return te(e)}),e.uint8Array=ee.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=ee.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=ee.fromAny(e=>BigInt(e))}(Tt||(Tt={}));const Nt=2n**255n-19n,Dt=2n**252n+27742317777372353535851937790883648493n,Mt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Pt=0x6666666666666666666666666666666666666666666666666666666666666658n,Lt={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Nt,n:Dt,h:8,Gx:Mt,Gy:Pt},Ht=(e="")=>{throw new Error(e)},Vt=e=>"string"==typeof e,Kt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Ht("Uint8Array of valid length expected"):e,Qt=e=>new Uint8Array(e),Ft=(e,t)=>Kt(Vt(e)?Xt(e):Qt(Kt(e)),t),$t=(e,t=Nt)=>{let r=e%t;return r>=0n?r:t+r},Gt=e=>e instanceof jt?e:Ht("Point expected");class jt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new jt(e.x,e.y,1n,$t(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Lt,s=(e=Ft(e,32)).slice(),i=e[31];s[31]=-129&i;const n=er(s);!t||0n<=n&&n<2n**256n||Ht("bad y coord 1"),t||0n<=n&&n<Nt||Ht("bad y coord 2");const a=$t(n*n),o=$t(a-1n),c=$t(r*a+1n);let{isValid:l,value:d}=nr(o,c);l||Ht("bad y coordinate 3");const u=1n==(1n&d),h=!!(128&i);return!t&&0n===d&&h&&Ht("bad y coord 3"),h!==u&&(d=$t(-d)),new jt(d,n,1n,$t(d*n))}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:a}=Gt(e),o=$t(t*a),c=$t(i*s),l=$t(r*a),d=$t(n*s);return o===c&&l===d}is0(){return this.equals(zt)}negate(){return new jt($t(-this.ex),this.ey,this.ez,$t(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Lt,i=$t(e*e),n=$t(t*t),a=$t(2n*$t(r*r)),o=$t(s*i),c=e+t,l=$t($t(c*c)-i-n),d=o+n,u=d-a,h=o-n,f=$t(l*u),g=$t(d*h),p=$t(l*h),b=$t(u*d);return new jt(f,g,b,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:a,ez:o,et:c}=Gt(e),{a:l,d}=Lt,u=$t(t*n),h=$t(r*a),f=$t(i*d*c),g=$t(s*o),p=$t((t+r)*(n+a)-u-h),b=$t(g-f),m=$t(g+f),y=$t(h-l*u),A=$t(p*b),I=$t(m*y),v=$t(p*y),w=$t(b*m);return new jt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Ht("cannot multiply by 0"):zt;if("bigint"==typeof e&&0n<e&&e<Dt||Ht("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(qt))return pr(e).p;let r=zt,s=qt;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(Lt.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Dt/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(zt))return{x:0n,y:1n};const s=rr(r,Nt);return 1n!==$t(r*s)&&Ht("invalid inverse"),{x:$t(e*s),y:$t(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Zt(t);return r[31]|=1n&e?128:0,r}toHex(){return Jt(this.toRawBytes())}}jt.BASE=new jt(Mt,Pt,1n,$t(Mt*Pt)),jt.ZERO=new jt(0n,1n,1n,0n);const{BASE:qt,ZERO:zt}=jt,Wt=(e,t)=>e.toString(16).padStart(t,"0"),Jt=e=>Array.from(Kt(e)).map(e=>Wt(e,2)).join(""),Yt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Xt=e=>{const t="hex invalid";if(!Vt(e))return Ht(t);const r=e.length,s=r/2;if(r%2)return Ht(t);const i=Qt(s);for(let r=0,n=0;r<s;r++,n+=2){const s=Yt(e.charCodeAt(n)),a=Yt(e.charCodeAt(n+1));if(void 0===s||void 0===a)return Ht(t);i[r]=16*s+a}return i},Zt=e=>Xt(Wt(e,64)).reverse(),er=e=>BigInt("0x"+Jt(Qt(Kt(e)).reverse())),tr=(...e)=>{const t=Qt(e.reduce((e,t)=>e+Kt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},rr=(e,t)=>{(0n===e||t<=0n)&&Ht("no inverse n="+e+" mod="+t);let r=$t(e,t),s=t,i=0n,n=1n,a=1n,o=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-a*e,l=n-o*e;s=r,r=t,i=a,n=o,a=c,o=l}return 1n===s?$t(i,t):Ht("no inverse")},sr=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Nt;return r},ir=19681161376707505956807079304988542015446066515923890162744021073123829784752n,nr=(e,t)=>{const r=$t(t*t*t),s=(e=>{const t=e*e%Nt*e%Nt,r=sr(t,2n)*t%Nt,s=sr(r,1n)*e%Nt,i=sr(s,5n)*s%Nt,n=sr(i,10n)*i%Nt,a=sr(n,20n)*n%Nt,o=sr(a,40n)*a%Nt,c=sr(o,80n)*o%Nt,l=sr(c,80n)*o%Nt,d=sr(l,10n)*i%Nt;return{pow_p_5_8:sr(d,2n)*e%Nt,b2:t}})(e*$t(r*r*t)).pow_p_5_8;let i=$t(e*r*s);const n=$t(t*i*i),a=i,o=$t(i*ir),c=n===e,l=n===$t(-e),d=n===$t(-e*ir);return c&&(i=a),(l||d)&&(i=o),1n==(1n&$t(i))&&(i=$t(-i)),{isValid:c||l,value:i}},ar=e=>$t(er(e),Dt);let or;const cr=(...e)=>fr.sha512Async(...e),lr=e=>{const t=e.slice(0,32);t[0]&=248,t[31]&=127,t[31]|=64;const r=e.slice(32,64),s=ar(t),i=qt.mul(s),n=i.toRawBytes();return{head:t,prefix:r,scalar:s,point:i,pointBytes:n}},dr=e=>cr(Ft(e,32)).then(lr);function ur(e,t){return e?cr(t.hashable).then(t.finish):t.finish(((...e)=>"function"==typeof or?or(...e):Ht("etc.sha512Sync not set"))(t.hashable))}const hr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,fr={bytesToHex:Jt,hexToBytes:Xt,concatBytes:tr,mod:$t,invert:rr,randomBytes:(e=32)=>{const t=hr();return t&&t.getRandomValues||Ht("crypto.getRandomValues must be defined"),t.getRandomValues(Qt(e))},sha512Async:async(...e)=>{const t=hr(),r=t&&t.subtle;r||Ht("etc.sha512Async or crypto.subtle must be defined");const s=tr(...e);return Qt(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let gr;Object.defineProperties(fr,{sha512Sync:{configurable:!1,get:()=>or,set(e){or||(or=e)}}});const pr=e=>{const t=gr||(gr=(()=>{const e=[];let t=qt,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=zt,i=qt;const n=BigInt(255),a=BigInt(8);for(let o=0;o<33;o++){const c=128*o;let l=Number(e&n);e>>=a,l>128&&(l-=256,e+=1n);const d=c,u=c+Math.abs(l)-1,h=o%2!=0,f=l<0;0===l?i=i.add(r(h,t[d])):s=s.add(r(f,t[u]))}return{p:s,f:i}};var br=a(625);const mr=32,yr=64;class Ar{pubKey;_privKey;constructor(e,t){this.pubKey=e,this._privKey=t}}async function Ir(e){const t=await(r=e.raw,dr(r).then(e=>e.pointBytes));var r;return new Ar(L.fromBlob(t,mr).asOpaque(),e.asOpaque())}async function vr(e,t){const r=await(async(e,t)=>{const r=Ft(e),s=await dr(t);return ur(!0,((e,t,r)=>{const{pointBytes:s,scalar:i}=e,n=ar(t),a=qt.mul(n).toRawBytes();return{hashable:tr(a,s,r),finish:e=>{const t=$t(n+ar(e)*i,Dt);return Kt(tr(a,Zt(t)),64)}}})(s,await cr(s.prefix,r),r))})(t.raw,e._privKey.raw);return L.fromBlob(r,yr).asOpaque()}async function wr(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+=mr,r.set(n.raw,s),s+=yr;const e=i.length;w(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,br.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}const Sr=L.blobFromString("jam_val_key_ed25519");L.blobFromString("jam_val_key_bandersnatch");class Er extends _{anchor;bitfield;validatorIndex;signature;static Codec=_e.Class(Er,{anchor:_e.bytes(Pe).asOpaque(),bitfield:kt(e=>_e.bitVecFixLen(e.coresCount)),validatorIndex:_e.u16.asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new Er(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const Cr=kt(e=>xt(Er.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),kr=e=>ee.array((e=>ee.object({anchor:Tt.bytes32(),bitfield:ee.fromString(t=>{const r=Math.ceil(e.coresCount/8);return J.fromBytes(L.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Tt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>Er.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class xr extends _{workReportHash;wasConsideredValid;key;signature;static Codec=_e.Class(xr,{workReportHash:_e.bytes(Pe).asOpaque(),wasConsideredValid:_e.bool,key:_e.bytes(mr).asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new xr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class _r extends _{workReportHash;key;signature;static Codec=_e.Class(_r,{workReportHash:_e.bytes(Pe).asOpaque(),key:_e.bytes(mr).asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new _r(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class Br extends _{isWorkReportValid;index;signature;static Codec=_e.Class(Br,{isWorkReportValid:_e.bool,index:_e.u16.asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new Br(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class Rr extends _{workReportHash;votesEpoch;votes;static Codec=_e.Class(Rr,{workReportHash:_e.bytes(Pe).asOpaque(),votesEpoch:_e.u32.asOpaque(),votes:kt(e=>ke(_e.sequenceFixLen(Br.Codec,e.validatorsSuperMajority)).convert(R,mt))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new Rr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class Or extends _{verdicts;culprits;faults;static Codec=_e.Class(Or,{verdicts:_e.sequenceVarLen(Rr.Codec),culprits:_e.sequenceVarLen(_r.Codec),faults:_e.sequenceVarLen(xr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new Or(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Ur=e=>ne(e),Tr=e=>se(e),Nr=e=>ne(e),Dr=e=>oe(e),Mr=e=>se(e),Pr=e=>ne(e);function Lr(e,t){return w(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Hr=e=>kt(t=>xt(e,{fixedLength:t.validatorsCount}));function Vr(e,t){return w(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Kr=e=>kt(t=>xt(e,{fixedLength:t.epochLength}));class Qr extends _{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=_e.Class(Qr,{anchor:_e.bytes(Pe).asOpaque(),stateRoot:_e.bytes(Pe).asOpaque(),beefyRoot:_e.bytes(Pe).asOpaque(),lookupAnchor:_e.bytes(Pe).asOpaque(),lookupAnchorSlot:_e.u32.asOpaque(),prerequisites:_e.sequenceVarLen(_e.bytes(Pe).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Qr(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 Fr extends _{treeRoot;index;static Codec=_e.Class(Fr,{treeRoot:_e.bytes(Pe),index:_e.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Fr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class $r extends _{hash;len;static Codec=_e.Class($r,{hash:_e.bytes(Pe).asOpaque(),len:_e.u32});static create({hash:e,len:t}){return new $r(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class Gr extends _{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=_e.Class(Gr,{service:_e.u32.asOpaque(),codeHash:_e.bytes(Pe).asOpaque(),payload:_e.blob,refineGasLimit:_e.u64.asOpaque(),accumulateGasLimit:_e.u64.asOpaque(),importSegments:xt(Fr.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:_e.sequenceVarLen($r.Codec),exportCount:_e.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:a,exportCount:o}){return new Gr(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=a,this.exportCount=o}}function jr(e){return S(e,e>=qr&&e<=zr,`WorkItemsCount: Expected '${qr} <= count <= ${zr}' got ${e}`)}const qr=1,zr=16;class Wr extends _{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=_e.Class(Wr,{authorization:_e.blob,authCodeHost:_e.u32.asOpaque(),authCodeHash:_e.bytes(Pe).asOpaque(),parametrization:_e.blob,context:Qr.Codec,items:_e.sequenceVarLen(Gr.Codec).convert(e=>e,e=>yt.new(e,jr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Wr(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 Jr,Yr;(Yr=Jr||(Jr={}))[Yr.ok=0]="ok",Yr[Yr.outOfGas=1]="outOfGas",Yr[Yr.panic=2]="panic",Yr[Yr.badCode=3]="badCode",Yr[Yr.codeOversize=4]="codeOversize";class Xr extends _{kind;okBlob;static Codec=_e.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===Jr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Jr.ok){const r=e.bytesBlob();return new Xr(t,r)}if(t>Jr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Xr(t)},e=>{e.decoder.varU32()===Jr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Zr extends _{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=_e.Class(Zr,{gasUsed:_e.varU64.asOpaque(),importedSegments:_e.varU32,extrinsicCount:_e.varU32,extrinsicSize:_e.varU32,exportedSegments:_e.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Zr(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 es{serviceId;codeHash;payloadHash;gas;result;load;static Codec=_e.Class(es,{serviceId:_e.u32.asOpaque(),codeHash:_e.bytes(Pe).asOpaque(),payloadHash:_e.bytes(Pe),gas:_e.u64.asOpaque(),result:Xr.Codec,load:Zr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new es(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 ts extends _{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=_e.Class(ts,{hash:_e.bytes(Pe).asOpaque(),length:_e.u32,erasureRoot:_e.bytes(Pe),exportsRoot:_e.bytes(Pe).asOpaque(),exportsCount:_e.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new ts(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 rs extends _{workPackageHash;segmentTreeRoot;static Codec=_e.Class(rs,{workPackageHash:_e.bytes(Pe).asOpaque(),segmentTreeRoot:_e.bytes(Pe).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new rs(e,t)}}class ss extends _{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=_e.Class(ss,{workPackageSpec:ts.Codec,context:Qr.Codec,coreIndex:v.isGreaterOrEqual(h.V0_6_5)&&!v.isSuite(f.JAMDUNA,h.V0_6_5)?_e.varU32.convert(e=>ne(e),e=>{if(!ie(e))throw new Error(`Core index exceeds U16: ${e}`);return Mr(e)}):_e.u16.asOpaque(),authorizerHash:_e.bytes(Pe).asOpaque(),authorizationOutput:_e.blob,segmentRootLookup:ke(_e.sequenceVarLen(rs.Codec)),results:_e.sequenceVarLen(es.Codec).convert(e=>e,e=>yt.new(e,jr(e.length))),authorizationGasUsed:_e.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:a,authorizationGasUsed:o}){return new ss(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=a,this.authorizationGasUsed=o}}const is=[2,3];class ns extends _{validatorIndex;signature;static Codec=_e.Class(ns,{validatorIndex:_e.u16.asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({validatorIndex:e,signature:t}){return new ns(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class as extends _{report;slot;credentials;static Codec=_e.Class(as,{report:ss.Codec,slot:_e.u32.asOpaque(),credentials:xt(ns.Codec,{minLength:is[0],maxLength:is[1],typicalLength:is[1]})});static create({report:e,slot:t,credentials:r}){return new as(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const os=kt(e=>xt(as.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class cs extends _{bandersnatch;ed25519;static Codec=_e.Class(cs,{bandersnatch:_e.bytes(Te).asOpaque(),ed25519:_e.bytes(mr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new cs(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class ls extends _{entropy;ticketsEntropy;validators;static Codec=_e.Class(ls,{entropy:_e.bytes(Pe).asOpaque(),ticketsEntropy:_e.bytes(Pe).asOpaque(),validators:Hr(cs.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new ls(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const ds=e=>{const t=e.encoded().raw,r=t.length-Ne;return P.blobFrom(t.subarray(0,r))};class us extends _{static Codec=_e.Class(us,{parentHeaderHash:_e.bytes(Pe).asOpaque(),priorStateRoot:_e.bytes(Pe).asOpaque(),extrinsicHash:_e.bytes(Pe).asOpaque(),timeSlotIndex:_e.u32.asOpaque(),epochMarker:_e.optional(ls.Codec),ticketsMarker:_e.optional(Kr(Ot.Codec)),offendersMarker:_e.sequenceVarLen(_e.bytes(mr).asOpaque()),bandersnatchBlockAuthorIndex:_e.u16.asOpaque(),entropySource:_e.bytes(Ne).asOpaque(),seal:_e.bytes(Ne).asOpaque()});static create(e){return Object.assign(us.empty(),e)}parentHeaderHash=L.zero(Pe).asOpaque();priorStateRoot=L.zero(Pe).asOpaque();extrinsicHash=L.zero(Pe).asOpaque();timeSlotIndex=Ur(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=Tr(0);entropySource=L.zero(Ne).asOpaque();seal=L.zero(Ne).asOpaque();constructor(){super()}static empty(){return new us}}class hs extends He{static Codec=_e.Class(hs,{hash:_e.bytes(Pe).asOpaque(),data:us.Codec.View});static create({hash:e,data:t}){return new He(e,t)}}const fs=hs.Codec;class gs extends _{requester;blob;static Codec=_e.Class(gs,{requester:_e.u32.asOpaque(),blob:_e.blob});static create({requester:e,blob:t}){return new gs(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const ps=_e.sequenceVarLen(gs.Codec);class bs extends _{tickets;preimages;guarantees;assurances;disputes;static Codec=_e.Class(bs,{tickets:Ut,preimages:ps,guarantees:os,assurances:Cr,disputes:Or.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new bs(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 ms extends _{header;extrinsic;static Codec=_e.Class(ms,{header:us.Codec,extrinsic:bs.Codec});static create({header:e,extrinsic:t}){return new ms(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ys=ee.object({target:Tt.bytes32(),vote:"boolean",key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>xr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),As=ee.object({target:Tt.bytes32(),key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,key:t,signature:r})=>_r.create({workReportHash:e,key:t,signature:r})),Is=ee.object({vote:"boolean",index:"number",signature:Tt.ed25519Signature},({vote:e,index:t,signature:r})=>Br.create({isWorkReportValid:e,index:t,signature:r})),vs=ee.object({target:Tt.bytes32(),age:"number",votes:ee.array(Is)},({target:e,age:t,votes:r})=>Rr.create({workReportHash:e,votesEpoch:t,votes:r})),ws=ee.object({verdicts:ee.array(vs),culprits:ee.array(As),faults:ee.array(ys)},({verdicts:e,culprits:t,faults:r})=>Or.create({verdicts:e,culprits:t,faults:r})),Ss=ee.object({anchor:Tt.bytes32(),state_root:Tt.bytes32(),beefy_root:Tt.bytes32(),lookup_anchor:Tt.bytes32(),lookup_anchor_slot:"number",prerequisites:ee.array(Tt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Qr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),Es=ee.object({ok:ee.optional(ee.fromString(P.parseBlob)),out_of_gas:ee.optional(ee.fromAny(()=>null)),panic:ee.optional(ee.fromAny(()=>null)),bad_code:ee.optional(ee.fromAny(()=>null)),code_oversize:ee.optional(ee.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 Xr(ne(Jr.ok),t);if(null===r)return new Xr(ne(Jr.outOfGas));if(null===s)return new Xr(ne(Jr.panic));if(null===i)return new Xr(ne(Jr.badCode));if(null===n)return new Xr(ne(Jr.codeOversize));throw new Error("Invalid WorkExecResult")}),Cs=ee.object({gas_used:ee.fromNumber(e=>Dr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Zr.create({gasUsed:Dr(e),importedSegments:ne(t),extrinsicCount:ne(r),extrinsicSize:ne(s),exportedSegments:ne(i)})),ks=ee.object({service_id:"number",code_hash:Tt.bytes32(),payload_hash:Tt.bytes32(),accumulate_gas:ee.fromNumber(e=>Dr(e)),result:Es,refine_load:Cs},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>es.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),xs=ee.object({hash:Tt.bytes32(),length:"number",erasure_root:Tt.bytes32(),exports_root:Tt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>ts.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),_s=ee.object({work_package_hash:Tt.bytes32(),segment_tree_root:Tt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>rs.create({workPackageHash:e,segmentTreeRoot:t})),Bs=ee.object({package_spec:xs,context:Ss,core_index:"number",authorizer_hash:Tt.bytes32(),auth_output:ee.fromString(P.parseBlob),segment_root_lookup:ee.array(_s),results:ee.array(ks),auth_gas_used:ee.fromNumber(e=>Dr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:a,auth_gas_used:o})=>{const c=yt.new(n,jr(n.length));return ss.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:a,results:c,authorizationGasUsed:o})}),Rs=ee.object({validator_index:"number",signature:Tt.ed25519Signature},({validator_index:e,signature:t})=>ns.create({validatorIndex:e,signature:t})),Os=ee.object({report:Bs,slot:"number",signatures:ee.array(Rs)},({report:e,slot:t,signatures:r})=>as.create({report:e,slot:t,credentials:r})),Us=ee.array(Os),Ts=ee.object({requester:"number",blob:ee.fromString(P.parseBlob)},({requester:e,blob:t})=>gs.create({requester:e,blob:t})),Ns=ee.array(Ts),Ds=ee.object({attempt:Tt.ticketAttempt,signature:ee.fromString(e=>L.parseBytes(e,784).asOpaque())},e=>Rt.create({attempt:e.attempt,signature:e.signature})),Ms=ee.array(Ds),Ps=ee.fromString(e=>L.parseBytes(e,96).asOpaque()),Ls=ee.object({bandersnatch:Tt.bytes32(),ed25519:Tt.bytes32()},cs.create),Hs=ee.object({entropy:Tt.bytes32(),tickets_entropy:Tt.bytes32(),validators:ee.array(Ls)},e=>ls.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),Vs=ee.object({id:Tt.bytes32(),attempt:Tt.ticketAttempt},e=>Ot.create({id:e.id,attempt:e.attempt})),Ks=ee.object({parent:Tt.bytes32(),parent_state_root:Tt.bytes32(),extrinsic_hash:Tt.bytes32(),slot:"number",epoch_mark:ee.optional(Hs),tickets_mark:ee.optional(ee.array(Vs)),offenders_mark:ee.array(Tt.bytes32()),author_index:"number",entropy_source:Ps,seal:Ps},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:a,author_index:o,entropy_source:c,seal:l})=>{const d=us.empty();return d.parentHeaderHash=e,d.priorStateRoot=t,d.extrinsicHash=r,d.timeSlotIndex=s,d.epochMarker=i??null,d.ticketsMarker=n??null,d.offendersMarker=a,d.bandersnatchBlockAuthorIndex=o,d.entropySource=c,d.seal=l,d}),Qs=t(import.meta.url)("node:timers/promises");var Fs;function $s(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)}}function Gs(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===Fs[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return Fs[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"}(Fs||(Fs={}));class js{options;static create(e,t){return e===Fs.TRACE?new qs(t):e===Fs.LOG?new zs(t):e===Fs.INFO?new Ws(t):new js(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(Fs.WARN,e,t,r)}error(e,t,r){this.push(Fs.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),a=$s(this.options,t),o=Fs[e].padEnd(5);if(e<a)return;const c=`${o} [${n}] ${s}\n\t@ ${i}`;e===Fs.WARN?console.warn(c):e===Fs.ERROR?console.error(c):console.info(c)}}class qs extends js{trace(e,t,r){this.push(Fs.TRACE,e,t,r)}log(e,t,r){this.push(Fs.LOG,e,t,r)}info(e,t,r){this.push(Fs.INFO,e,t,r)}}class zs extends js{trace(e,t,r){}log(e,t,r){this.push(Fs.LOG,e,t,r)}info(e,t,r){this.push(Fs.INFO,e,t,r)}}class Ws extends js{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(Fs.INFO,e,t,r)}}const Js={workingDir:"",defaultLevel:Fs.LOG,modules:new Map},Ys={options:Js,transport:js.create(Js.defaultLevel,Js)};class Xs{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new Xs(t??r,r,Ys)}static getLevel(e){return $s(Ys.options,e)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=js.create(t,e);Ys.options=e,Ys.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(),Gs(r.trim()))}else n=Gs(t)}const a="".split("/");return a.pop(),a.pop(),{defaultLevel:n,modules:s,workingDir:r??a.join("/")}}(e,t,r);Xs.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)}}var Zs;!function(e){e[e.NOTSET=0]="NOTSET",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=100]="SILENT"}(Zs||(Zs={}));const ei="captureStackTrace"in Error,ti="stackTraceLimit"in Error;function ri(e){switch(e){case Zs.NOTSET:return"NOTSET";case Zs.DEBUG:return"DEBUG";case Zs.INFO:return"INFO";case Zs.WARN:return"WARN";case Zs.ERROR:return"ERROR";case Zs.SILENT:return"SILENT"}}function si(e,t){return"function"==typeof t?t():t}function ii(e){return JSON.stringify(e,si)}const ni=Symbol("level"),ai=Symbol("key"),oi=Symbol("keys"),ci=Symbol("date"),li=Symbol("msg"),di=Symbol("stack"),ui=Symbol("data");function hi(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===ai)s+=r.key;else if(n===oi)s+=r.keys;else if(n===ci)s+=r.date().toISOString();else if(n===li)null!=r.msg&&(s+=r.msg);else if(n===ni)s+=ri(r.level);else if(n===ui)s+=ii(r.data);else if(n===di){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}}const fi=hi`${ni}:${ai}:${li}`,gi=class{formatter;constructor(e=fi){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)}},pi=class extends gi{emit(e){console.error(e)}};class bi{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Zs.NOTSET,r=[new pi],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 bi(e,Zs.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!==Zs.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,{},Zs.DEBUG,t):this.log(e,t,Zs.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Zs.INFO,t):this.log(e,t,Zs.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Zs.WARN,t):this.log(e,t,Zs.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Zs.ERROR,t):this.log(e,t,Zs.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(ei&&ti){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,bi.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 mi=bi,yi=t(import.meta.url)("node:process"),Ai=class extends gi{emit(e){yi.stderr.write(e+"\n")}},Ii=t(import.meta.url)("dgram");class vi 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 wi=vi;class Si extends wi{constructor(e){super(Si.name,e,arguments)}}const Ei=Si;class Ci extends wi{constructor(e){super(Ci.name,e,arguments)}}const ki=Ci;class xi extends wi{constructor(e){super(xi.name,e,arguments)}}const _i=xi,Bi=Symbol("_eventTarget"),Ri=Symbol("eventTarget"),Oi=Symbol("_eventHandlers"),Ui=Symbol("eventHandlers"),Ti=Symbol("_eventHandled"),Ni=Symbol("eventHandled"),Di=Symbol("_handleEventError"),Mi=Symbol("handleEventError");function Pi(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function Li(e,t){return e.capture===t.capture}function Hi(){return e=>{const t=class extends e{[Bi]=new EventTarget;[Oi]=new Map;[Ti]=new WeakSet;[Di]=e=>{throw e.detail};constructor(...e){super(...e),this[Bi].addEventListener(_i.name,this[Di])}get[Ri](){return this[Bi]}get[Ui](){return this[Oi]}get[Ni](){return this[Ti]}get[Mi](){return this[Di]}addEventListener(e,t,r){r=Pi(r);const s=this;let i,n,a=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[Oi].get(e),void 0===n&&(n=new Set,this[Oi].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,Li(e.options,r))){a=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[Ti].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new _i({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new _i({detail:e}))}},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[Ti].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new _i({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new _i({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):i=t,this[Bi].addEventListener(e,i,r),e===_i.name&&1===n?.size&&this[Bi].removeEventListener(_i.name,this[Di])}removeEventListener(e,t,r){let s,i,n;if(r=Pi(r),null!=t){if(i=this[Oi].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&Li(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[Bi].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===_i.name&&0===i.size&&this[Bi].addEventListener(_i.name,this[Di]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof _i)return this[Bi].dispatchEvent(e);{let t=this[Bi].dispatchEvent(e);if(t&&!this[Ti].has(e)){const r=new Ei({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[Bi].dispatchEvent(r)}if(t){const r=new ki({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[Bi].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function Vi(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*Ki(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 Qi extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof Qi?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 a=super.then(i,n),o=Qi.from(a,r);return s=o.abortController.signal,o}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 Fi=Qi,$i=t(import.meta.url)("node:perf_hooks");var Gi,ji=(Gi=function(e,t){return Gi=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])},Gi(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}Gi(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),qi=function(e){function t(t){var r,s,i,n=this.constructor,a=e.call(this,t)||this;return Object.defineProperty(a,"name",{value:n.name,enumerable:!1,configurable:!0}),r=a,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)}(a),a}return ji(t,e),t}(Error);const zi=class extends qi{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($i.performance.timeOrigin+$i.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 Wi(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=Wi(s,t,r);if(e)return e}return Wi(e.cause,t,r)}return e instanceof Error&&Wi(e.cause,t,r)}class Ji extends zi{static description="Timer error"}class Yi extends Ji{static description="The timer has already ended"}class Xi{_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 Fi((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($i.performance.timeOrigin+$i.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date($i.performance.timeOrigin+$i.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()-($i.performance.timeOrigin+$i.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 Yi;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Yi;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date($i.performance.timeOrigin+$i.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 Zi=Xi;function en(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function tn(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new Zi(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Zi&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new Zi(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new Fi((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}class rn extends zi{static description="Async locks error"}class sn extends rn{static description="Async locks timeout"}const nn=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}:{},()=>tn((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=en();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 a=!1;const o={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{a||(a=!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,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,sn,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}:{},tn((e,t)=>{const{p:r,resolveP:s,rejectP:i}=en();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)},a={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,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,sn,r,[t])}withF(...e){const t=e.pop();return Vi([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Ki([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()}}},an=class{semaphore=new nn(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 Vi([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Ki([this.lock(...e)],([e])=>t(e))}},on=class{readersLock=new an;writersLock=new an;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}:{},()=>tn(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,sn,e,[])}write(e){return e=null!=e?{...e}:{},()=>tn(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,sn,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return Fi.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 Vi([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return Vi([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 Ki([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return Ki([this.write(...e)],([e])=>t(e))}},cn=Symbol("_running"),ln=Symbol("running"),dn=Symbol("_destroyed"),un=Symbol("destroyed"),hn=Symbol("_status"),fn=Symbol("status"),gn=Symbol("_statusP"),pn=Symbol("statusP"),bn=Symbol("resolveStatusP"),mn=Symbol("initLock"),yn=(async()=>{}).constructor,An=function*(){}.constructor,In=async function*(){}.constructor,vn="captureStackTrace"in Error;function wn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Sn(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);vn?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class En extends wi{}class Cn extends En{}class kn extends En{}class xn extends En{}class _n extends En{}class Bn extends En{}class Rn extends En{}class On extends zi{static description="Async init error"}class Un extends On{static description="Async init is not running"}class Tn extends On{static description="Async init is destroyed"}function Nn({eventDestroy:e=Bn,eventDestroyed:t=Rn}={}){return r=>{const{p:s,resolveP:i}=wn(),n=class extends(Hi()(r)){[dn]=!1;[hn]=null;[gn]=s;[bn]=i;[mn]=new on;get[un](){return this[dn]}get[fn](){return this[hn]}get[pn](){return this[gn]}async destroy(...r){return this[mn].withWriteF(async()=>{if(this[dn])return;this[hn]="destroying",this[bn]("destroying");const{p:s,resolveP:i}=wn();let n;return this[gn]=s,this[bn]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[dn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[hn]=null,this[bn](null);const{p:e,resolveP:t}=wn();this[gn]=e,this[bn]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function Dn(e=new Tn,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof yn?async function(...s){if(this[mn].isLocked("write")&&null===this[hn]&&await this[gn],r.includes(this[hn]))return o.apply(this,s);if(t)return this[mn].withReadF(async()=>{if(this[dn])throw Sn(e,n[a]),e;return o.apply(this,s)});if(this[mn].isLocked("write")||this[dn])throw Sn(e,n[a]),e;return o.apply(this,s)}:o instanceof An?function*(...t){if(r.includes(this[hn]))return yield*o.apply(this,t);if(this[mn].isLocked("write")&&null!==this[fn]||this[dn])throw Sn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof In?async function*(...s){if(this[mn].isLocked("write")&&null===this[hn]&&await this[gn],r.includes(this[hn]))return yield*o.apply(this,s);if(t)return yield*this[mn].withReadG(()=>{if(this[dn])throw Sn(e,n[a]),e;return o.apply(this,s)});if(this[mn].isLocked("write")||this[dn])throw Sn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[hn]))return o.apply(this,t);if(this[mn].isLocked("write")&&null!==this[fn]||this[dn])throw Sn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}function Mn({eventStart:e=Cn,eventStarted:t=kn,eventStop:r=xn,eventStopped:s=_n}={}){return i=>{const{p:n,resolveP:a}=wn(),o=class extends(Hi()(i)){[cn]=!1;[hn]=null;[gn]=n;[bn]=a;[mn]=new on;get[ln](){return this[cn]}get[fn](){return this[hn]}get[pn](){return this[gn]}async start(...r){return this[mn].withWriteF(async()=>{if(this[cn])return;this[hn]="starting",this[bn]("starting");const{p:s,resolveP:i}=wn();let n;return this[gn]=s,this[bn]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[cn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[hn]=null,this[bn](null);const{p:e,resolveP:t}=wn();this[gn]=e,this[bn]=t})}async stop(...e){return this[mn].withWriteF(async()=>{if(!this[cn])return;this[hn]="stopping",this[bn]("stopping");const{p:t,resolveP:i}=wn();let n;return this[gn]=t,this[bn]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[cn]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[hn]=null,this[bn](null);const{p:e,resolveP:t}=wn();this[gn]=e,this[bn]=t})}};return Object.defineProperty(o,"name",Object.getOwnPropertyDescriptor(i,"name")),o}}function Pn(e=new Un,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof yn?async function(...s){if(this[mn].isLocked("write")&&null===this[hn]&&await this[gn],r.includes(this[hn]))return o.apply(this,s);if(t)return this[mn].withReadF(async()=>{if(!this[cn])throw Sn(e,n[a]),e;return o.apply(this,s)});if(this[mn].isLocked("write")||!this[cn])throw Sn(e,n[a]),e;return o.apply(this,s)}:o instanceof An?function*(...t){if(r.includes(this[hn]))return yield*o.apply(this,t);if(this[mn].isLocked("write")&&null!==this[fn]||!this[cn])throw Sn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof In?async function*(...s){if(this[mn].isLocked("write")&&null===this[hn]&&await this[gn],r.includes(this[hn]))return yield*o.apply(this,s);if(t)return yield*this[mn].withReadG(()=>{if(!this[cn])throw Sn(e,n[a]),e;return o.apply(this,s)});if(this[mn].isLocked("write")||!this[cn])throw Sn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[hn]))return o.apply(this,t);if(this[mn].isLocked("write")&&null!==this[fn]||!this[cn])throw Sn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}class Ln 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 Hn=Ln;class Vn{[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,Hn.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,Hn.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:[Hn.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[Hn.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 Kn=Vn,Qn="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",Fn=t(import.meta.url)("dns"),$n=t(import.meta.url)("node:events");var Gn=a.n($n),jn=a(618);class qn extends zi{static description="QUIC error"}class zn extends zi{static description="You should never see this error"}class Wn extends zi{static description="Host provided was not valid"}class Jn extends zi{static description="Port provided was not valid"}class Yn extends qn{static description="QUIC config error"}class Xn extends qn{static description="QUIC Socket error"}class Zn extends Xn{static description="QUIC Socket is not running"}class ea extends Xn{static description="QUIC Socket has active connections"}class ta extends Xn{static description="QUIC Socket cannot bind to the specified address"}class ra extends Xn{static description="QUIC Socket cannot send to the specified address"}class sa extends Xn{static description="QUIC Socket internal error"}class ia extends qn{static description="QUIC Client error"}class na extends ia{static description="QUIC Client is destroyed"}class aa extends ia{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class oa extends ia{static description="QUIC Client had a failure relating to an invalid argument"}class ca extends ia{static description="QUIC Client cannot be created with the specified host"}class la extends ia{static description="QUIC Client internal error"}class da extends qn{static description="QUIC Server error"}class ua extends da{static description="QUIC Server is not running"}class ha extends da{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class fa extends da{static description="QUIC Server creating a new connection"}class ga extends da{static description="QUIC Server internal error"}class pa extends da{static description="QUIC Server is stopping"}class ba extends qn{static description="QUIC Connection error"}class ma extends ba{static description="QUIC Connection is stopping"}class ya extends ba{static description="QUIC Connection is not running"}class Aa extends ba{static description="QUIC Connection cannot be restarted because it has already been closed"}class Ia extends qn{static description="QUIC Connection start requires data when it is a server connection"}class va extends ba{static description="QUIC connection invalid configuration"}class wa extends ba{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class Sa extends wa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Ea extends ba{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class Ca extends wa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class ka extends ba{static description="QUIC Connection max idle timeout exhausted"}class xa extends ba{static description="QUIC Connection internal error"}class _a extends qn{static description="QUIC Stream error"}class Ba extends _a{static description="QUIC Stream is destroyed"}class Ra extends _a{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class Oa extends _a{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class Ua extends _a{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class Ta extends _a{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class Na extends _a{static description="QUIC Stream internal error"}class Da extends _a{static description="QUIC Stream limit has been reached"}const Ma=new TextEncoder,Pa=new TextDecoder("utf-8");function La(e){throw new zn(e)}function Ha(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 Va(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ka(e){const[t]=jn.Validator.isValidIPv4String(e);return t}function Qa(e){const[t]=jn.Validator.isValidIPv6String(e);return!!t||Fa(e)}function Fa(e){if(e.startsWith("::ffff:"))try{return jn.IPv6.fromString(e),!0}catch{if(Ka(e.slice(7)))return!0}return!1}function $a(e){if(!Ka(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function Ga(e){const t=e.slice(7);if(Ka(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 ja(e){const t=new jn.IPv4("0.0.0.0"),r=new jn.IPv6("::");if(Fa(e)){const r=Ga(e);return new jn.IPv4(r).isEquals(t)?$a("127.0.0.1"):e}return Ka(e)&&new jn.IPv4(e).isEquals(t)?"127.0.0.1":Qa(e)&&new jn.IPv6(e).isEquals(r)?"::1":e}async function qa(e){return(await Fn.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function za(e,t){if(Ka(e))return[e,"udp4"];if(Qa(e))return[e,"udp6"];try{return za(e=await t(e),t)}catch{throw new Wn}}function Wa(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new Jn;return e}function Ja(e,t=0){let r;return r=Ka(e)?`${e}:${t}`:Qa(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Ya(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 a=Fa(e),o=Fa(r);if("ipv4&ipv6"===t&&"udp4"===s)return $a(r);if("ipv4"===t){if(a){if("udp4"===s)return $a(r);if("udp6"===s&&!o)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(o)return Ga(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||o)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function Xa(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(Pa.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(Pa.decode(r).trim()+"\n");return t}function Za(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function eo(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function to(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function ro(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function so(e,t=1e5){$n.setMaxListeners(t,e)}class io extends wi{}class no extends io{}class ao extends no{}class oo extends no{}class co extends no{}class lo extends io{}class uo extends lo{}class ho extends no{}class fo extends lo{}class go extends io{}class po extends go{}class bo extends go{}class mo extends go{}class yo extends io{}class Ao extends yo{}class Io extends yo{}class vo extends yo{}class wo extends yo{}class So extends yo{}class Eo extends io{}class Co extends Eo{}class ko extends Eo{}class xo extends Eo{}class _o extends Eo{}class Bo extends Eo{}var Ro=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let Oo=class{connectionMap=new Kn;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(eo(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[ln]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=Qn.Header.fromSlice(e,Qn.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new Hn(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(Wi(e,e=>e instanceof Xn)){const t=new sa("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new oo({detail:t})),void this.dispatchEvent(new co)}if(e instanceof fa)return;throw e}}};constructor({resolveHostname:e=qa,logger:t}){this.logger=t??new mi(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=Va();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}={}){so(this[Bi]);let i=Ja(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,a]=await za(e,this.resolveHostname),o=Wa(t);this.socket=Ii.createSocket({type:a,reuseAddr:r,ipv6Only:s}),this.socketBind=Ha(this.socket.bind).bind(this.socket),this.socketClose=Ha(this.socket.close).bind(this.socket),this.socketSend=Ha(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=Va();c.catch(()=>{}),this.socket.once("error",l);const d=this.socketBind(o,n);try{await Promise.race([d,c])}catch(t){throw new ta(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"===a||Fa(n)?this._type="ipv4":"udp6"===a&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(oo.name,this.handleEventQUICSocketError),this.addEventListener(co.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=Ja(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=Ja(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new ea(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new co),await this._closedP;const{p:r,resolveP:s}=Va();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(oo.name,this.handleEventQUICSocketError),this.removeEventListener(co.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 za(r,this.resolveHostname);return s=ja(s),s=Ya(this._host,this._type,s,i,ra),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};Ro([Pn(new Zn)],Oo.prototype,"host",null),Ro([Pn(new Zn)],Oo.prototype,"port",null),Ro([Pn(new Zn)],Oo.prototype,"type",null),Ro([Pn(new Zn)],Oo.prototype,"send",null),Ro([Pn(new Zn)],Oo.prototype,"send_",null),Oo=Ro([Mn({eventStart:class extends no{},eventStarted:class extends no{},eventStop:class extends no{},eventStopped:ao})],Oo);const Uo=Oo,To=new WeakMap;const No=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(To.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);To.set(i,r)};class Do extends zi{static description="Contexts error"}class Mo extends Do{static description="Aborted due to timer expiration"}const Po=function(e=!1,t=1/0,r=Mo){return(s,i,n)=>{const a=s.name??s.constructor.name,o=n.value;if("function"!=typeof o)throw new TypeError(`\`${a}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=To.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,a);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 Zi))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,a),function(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new Zi(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Zi&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new Zi(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new Fi((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}((e,...t)=>o.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}},Lo=["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(":"),Ho=1/0,Vo={sigalgs:Lo,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Qn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Qn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Qn.MAX_CONNECTION_WINDOW,maxStreamWindow:Qn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Ko={sigalgs:Lo,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Qn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Qn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Qn.MAX_CONNECTION_WINDOW,maxStreamWindow:Qn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Qo=t(import.meta.url)("stream/web");var Fo=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};const $o=Symbol("abort readableP reason");let Go=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:a=new mi(`${this.name} ${t}`)}){a.info(`Create ${this.name}`);const o=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a});return"uni"===o.type&&("local"===e?(o.readableController.close(),o._readClosed=!0):"peer"===e&&(o.writable.close().catch(()=>{}),o._writeClosed=!0)),o.addEventListener(ko.name,o.handleEventQUICStreamError),o.addEventListener(xo.name,o.handleEventQUICStreamCloseRead,{once:!0}),o.addEventListener(_o.name,o.handleEventQUICStreamCloseWrite,{once:!0}),a.info(`Created ${this.name}`),o}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 Na)throw this.logger.debug(eo(t)),t;t instanceof Ra||t instanceof Ua?this.dispatchEvent(new xo({detail:t})):(t instanceof Oa||t instanceof Ta)&&this.dispatchEvent(new _o({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[un]||"destroying"===this[fn]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[un]||"destroying"===this[fn]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=a,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:o,resolveP:c}=Va();if(this.closedP=o,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 Qo.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new Qo.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new Qo.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new Qo.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new Qo.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===to(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new Da(`Stream limit of ${t} has been reached`,{cause:e})}throw new Na(`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(ko.name,this.handleEventQUICStreamError),this.removeEventListener(xo.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(_o.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=ro(e))){const e=this.codeToReason("read",t),r=new Ua("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new ko({detail:r}))}{const t=new Na("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new ko({detail:t})),t}}if(null===e){const e=new Na("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new ko({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 xo),void this.rejectReadableP?.($o)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=to(e))){this.connection.conn.streamShutdown(this.streamId,Qn.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new Ta("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new ko({detail:r}))}{const t=new Na("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new ko({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}=Va();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=ro(e))){const e=this.codeToReason("read",t),r=new Ua("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new ko({detail:r}))}{const t=new Na("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new ko({detail:t})),t}}if(null===e){const e=new Na("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new ko({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 xo)),this.dispatchEvent(new Bo)}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=to(e))){const e=this.codeToReason("write",t),r=new Ta("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new ko({detail:r}))}{const t=new Na("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new ko({detail:t})),t}}if(this.dispatchEvent(new Bo),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=Va();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=to(e))){const e=this.codeToReason("write",t),r=new Ta("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new ko({detail:r}))}{const t=new Na("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new ko({detail:t})),t}}this.dispatchEvent(new _o),this.dispatchEvent(new Bo)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,Qn.Shutdown.Read,t)}catch(r){const e=new Na("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new ko({detail:e})),e}const r=new Ra("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new ko({detail:r})),this.dispatchEvent(new Bo)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,Qn.Shutdown.Write,t)}catch(r){const e=new Na("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new ko({detail:e})),e}const r=new Oa("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new ko({detail:r})),this.dispatchEvent(new Bo)}};Fo([Dn(new Ba)],Go.prototype,"meta",null),Fo([Dn(new Ba,!1,["destroying"])],Go.prototype,"read",null),Fo([Dn(new Ba,!1,["destroying"])],Go.prototype,"write",null),Go=Fo([Nn({eventDestroy:class extends Eo{},eventDestroyed:Co})],Go);const jo=Go;var qo,zo,Wo,Jo,Yo;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(qo||(qo={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(zo||(zo={})),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"}(Wo||(Wo={})),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"}(Jo||(Jo={})),function(e){e[e.CloseNotify=256]="CloseNotify",e[e.UnexpectedMessage=266]="UnexpectedMessage",e[e.BadRecordMac=276]="BadRecordMac",e[e.RecordOverflow=278]="RecordOverflow",e[e.HandshakeFailure=296]="HandshakeFailure",e[e.BadCertificate=298]="BadCertificate",e[e.UnsupportedCertificate=299]="UnsupportedCertificate",e[e.CertificateRevoked=300]="CertificateRevoked",e[e.CertificateExpired=301]="CertificateExpired",e[e.CertificateUnknown=302]="CertificateUnknown",e[e.IllegalParameter=303]="IllegalParameter",e[e.UnknownCA=304]="UnknownCA",e[e.AccessDenied=305]="AccessDenied",e[e.DecodeError=306]="DecodeError",e[e.DecryptError=307]="DecryptError",e[e.ProtocolVersion=326]="ProtocolVersion",e[e.InsufficientSecurity=327]="InsufficientSecurity",e[e.InternalError=336]="InternalError",e[e.InappropriateFallback=342]="InappropriateFallback",e[e.UserCanceled=346]="UserCanceled",e[e.MissingExtension=365]="MissingExtension",e[e.UnsupportedExtension=366]="UnsupportedExtension",e[e.UnrecognizedName=368]="UnrecognizedName",e[e.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",e[e.UnknownPSKIdentity=371]="UnknownPSKIdentity",e[e.CertificateRequired=372]="CertificateRequired",e[e.NoApplicationProtocol=376]="NoApplicationProtocol"}(Yo||(Yo={}));var Xo=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let Zo=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new an;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(eo(t)),t instanceof xa)throw t;this.dispatchEvent(new vo({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof wa&&await this.send(),this[ln]&&"stopping"!==this[fn]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof wi&&!(e.detail instanceof Bo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[ln]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(Bo.name,this.handleEventQUICStreamSend),t.removeEventListener(ki.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:a,reasonToCode:o=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new mi(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new va("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const d=function(e){if(null!=e.key&&null==e.cert)throw new Yn("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new Yn("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 Yn("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Xa(e.ca);t=Ma.encode(r.join(""))}null!=e.key&&(r=Xa(e.key).map(e=>Ma.encode(e))),null!=e.cert&&(s=Xa(e.cert).map(e=>Ma.encode(e)));try{i=Qn.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new Yn(`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=Qn.Connection.connect(s,t,{host:a.host,port:a.port},{host:i.host,port:i.port},d)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=Qn.Connection.accept(t,r,{host:a.host,port:a.port},{host:i.host,port:i.port},d)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=a,this.config=n,null!=this.config.cert){const e=Xa(this.config.cert);this.certDERs=e.map(Za)}if(null!=this.config.ca){const e=Xa(this.config.ca);this.caDERs=e.map(Za)}this.reasonToCode=o,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:h,resolveP:f,rejectP:g}=Va();h.catch(()=>{}),this.secureEstablishedP=h,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=g;const{p,resolveP:b}=Va();this.closedP=p,this.resolveClosedP=b}get connectionId(){const e=this.conn.sourceId();return new Hn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new Hn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new Hn(Buffer.concat([e,t])):new Hn(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 Aa;r.signal.throwIfAborted();const{p:s,rejectP:i}=Va();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Io.name,this.handleEventQUICConnectionError),this.addEventListener(vo.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new Ia("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,Qn.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,Qn.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,Jo.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new wa("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Io({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 wa(i,{data:s});this.dispatchEvent(new Io({detail:n}))}await this.closedP,this.removeEventListener(Io.name,this.handleEventQUICConnectionError),this.removeEventListener(vo.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 xa("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Io({detail:t})),t}{let r;return r="TlsFail"===e.message?new Sa("Failed connection due to native TLS verification",{cause:e,data:t}):new wa("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Io({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 xa("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Io({detail:t})),t}this.dispatchEvent(new So({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 Sa("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Io({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[fn]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=Qn.CRYPTO_ERROR_START&&e.errorCode<=Qn.CRYPTO_ERROR_STOP?this.dispatchEvent(new Io({detail:new Ca(t,{data:e})})):this.dispatchEvent(new Io({detail:new Ea(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:La("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[ln]||"stopping"===this[fn]){this.conn.streamShutdown(e,zo.Write,this.reasonToCode("write",ma)),this.conn.streamShutdown(e,zo.Read,this.reasonToCode("read",ma));continue}this.isStreamUsed(e)&&La("We should never repeat streamIds when creating streams"),t=jo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${jo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Bo.name,this.handleEventQUICStreamSend),t.addEventListener(Co.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ki.name,this.handleEventQUICStream),this.dispatchEvent(new wo({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[ln]||"stopping"===this[fn]){this.conn.streamShutdown(e,zo.Write,this.reasonToCode("write",ma)),this.conn.streamShutdown(e,zo.Read,this.reasonToCode("read",ma));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==to(e))continue;if("FinalSize"===e.message)continue;throw e}La("We never expect a duplicate stream to be readable")}t=jo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${jo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Bo.name,this.handleEventQUICStreamSend),t.addEventListener(Co.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ki.name,this.handleEventQUICStream),this.dispatchEvent(new wo({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 Io({detail:new ka})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new Zi({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 Io({detail:new ka}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new Zi({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)&&La("We should never repeat streamIds when creating streams");const r=jo.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${jo.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(Bo.name,this.handleEventQUICStreamSend),r.addEventListener(Co.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(ki.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 Zi({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new Zi({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var ec,tc;Xo([Pn(new ya)],Zo.prototype,"connectionIdPeer",null),Xo([Pn(new ya)],Zo.prototype,"connectionIdShared",null),Xo([Po(!0,Ho,class extends ba{static description="QUIC Connection start timeout"}),(ec=1,tc=No,function(e,t){tc(e,t,ec)})],Zo.prototype,"start",null),Xo([Pn(new ya,!1,["starting","stopping"])],Zo.prototype,"recv",null),Xo([Pn(new ya,!1,["starting","stopping"])],Zo.prototype,"send",null),Xo([Pn(new ya)],Zo.prototype,"newStream",null),Zo=Xo([Mn({eventStart:class extends yo{},eventStarted:class extends yo{},eventStop:class extends yo{},eventStopped:Ao})],Zo);const rc=Zo;var sc=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let ic=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(eo(t)),t instanceof ga)throw t;this.dispatchEvent(new mo({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof ha||this.isSocketShared)){this.socket.removeEventListener(ao.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new ga("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new bo({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[ln]&&"stopping"!==this[fn]&&(void 0!==t?await this.stop({isApp:!1,errorCode:Jo.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof wi&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new ha;this.removeEventListener(ki.name,this.handleEventQUICSocket),this.dispatchEvent(new bo({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof wi&&!(e.detail instanceof So)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[ln]&&"stopping"!==this.socket[fn])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 ho(`${ho.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new bo({detail:new ga("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(So.name,this.handleEventQUICConnectionSend),t.removeEventListener(ki.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=qa,reasonToCode:i,codeToReason:n,minIdleTimeout:a,logger:o}){this.logger=o??new mi(this.constructor.name),this.crypto=e,null==r?(this.socket=new Uo({resolveHostname:s,logger:this.logger.getChild(Uo.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...Ko,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=a;const{p:c,resolveP:l}=Va();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,so(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[ln])throw new ha;i=Ja(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=Ja(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=Ja(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(bo.name,this.handleEventQUICServerError),this.addEventListener(mo.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(ao.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(ki.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[ln]&&(i=Ja(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 pa),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 mo),await this._closedP;const{p:a,resolveP:o}=Va();this._closedP=a,this.resolveClosedP=o,this.removeEventListener(bo.name,this.handleEventQUICServerError),this.removeEventListener(mo.name,this.handleEventQUICServerClose),this.socket.removeEventListener(ao.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ki.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==Qn.Type.Initial&&t.ty!==Qn.Type.ZeroRTT)return;const i=new Hn(await this.crypto.ops.sign(this.crypto.key,r),0,Qn.MAX_CONN_ID_LEN),n=Ja(e.host,e.port);if(!Qn.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(Qn.MAX_DATAGRAM_SIZE),s=Qn.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new fa(`Failed to send version datagram ${n}`,{cause:e})}return}const a=t.token;if(0===a.byteLength){const s=await this.mintToken(r,e.host),a=Buffer.allocUnsafe(Qn.MAX_DATAGRAM_SIZE),o=Qn.retry(t.scid,t.dcid,i,s,t.version,a);try{await this.socket.send_(a,0,o,e.port,e.host)}catch(e){throw new fa(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const o=await this.validateToken(Buffer.from(a),e.host);if(null==o)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new Hn(t.dcid),l=new rc({type:"server",scid:c,dcid:o,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${rc.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(So.name,this.handleEventQUICConnectionSend),l.addEventListener(Ao.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(ki.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(So.name,this.handleEventQUICConnectionSend),l.removeEventListener(Ao.name,this.handleEventQUICConnectionStopped),l.removeEventListener(ki.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new fa("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new po({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),a=Buffer.from(await r.ops.sign(r.key,n)),o={msg:n.toString("base64url"),sig:a.toString("base64url")},c=JSON.stringify(o);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 a;try{a=JSON.parse(i.toString())}catch{return}return"object"==typeof a&&null!=a&&"string"==typeof a.dcid&&"string"==typeof a.host&&a.host===t?Hn.fromString(a.dcid):void 0}(e,t,this.crypto)}};sc([Pn(new ua)],ic.prototype,"host",null),sc([Pn(new ua)],ic.prototype,"port",null),sc([Pn(new ua)],ic.prototype,"acceptConnection",null),ic=sc([Mn({eventStart:class extends go{},eventStarted:class extends go{},eventStop:class extends go{},eventStopped:class extends go{}})],ic);const nc=ic;var ac=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let oc=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:a,config:o={},resolveHostname:c=qa,reuseAddr:l,ipv6Only:d,reasonToCode:u,codeToReason:h,logger:f=new mi(`${this.name}`)},g){let p=Ja(e,t);f.info(`Create ${this.name} to ${p}`);const b={...Vo,...o},m=new ArrayBuffer(Qn.MAX_CONN_ID_LEN);await a.ops.randomBytes(m);const y=new Hn(m);let[A,I]=await za(e,c);const v=Wa(t);let w,S;if(A=ja(A),null==n){const[e]=await za(s,c),t=Wa(i);n=new Uo({resolveHostname:c,logger:f.getChild(Uo.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:d})}else if(w=!0,!n[ln])throw new ha;try{A=Ya(n.host,n.type,A,I,ca)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new rc({type:"client",scid:y,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:b,reasonToCode:u,codeToReason:h,logger:f.getChild(`${rc.name} ${y.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:f});w||n.addEventListener(ki.name,E.handleEventQUICSocket),n.addEventListener(ao.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(ki.name,E.handleEventQUICConnection),S.addEventListener(Io.name,E.handleEventQUICConnectionError),S.addEventListener(So.name,E.handleEventQUICConnectionSend),S.addEventListener(Ao.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(uo.name,E.handleEventQUICClientError),E.addEventListener(fo.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(g.signal.reason)};g.signal.aborted?C.abort(g.signal.reason):g.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new oa(void 0,{cause:e.detail}))}};E.addEventListener(`${ho.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:g.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(ao.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(ki.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(ki.name,E.handleEventQUICConnection),S.removeEventListener(Io.name,E.handleEventQUICConnectionError),S.removeEventListener(So.name,E.handleEventQUICConnectionSend),S.removeEventListener(Ao.name,E.handleEventQUICConnectionStopped),E.removeEventListener(uo.name,E.handleEventQUICClientError),E.removeEventListener(fo.name,E.handleEventQUICClientClose),e}finally{g.signal.removeEventListener("abort",k),E.removeEventListener(`${ho.name}-${S.sendId}`,x)}return p=Ja(A,t),f.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(eo(t)),t instanceof la||t instanceof xa)throw t;this.dispatchEvent(new fo({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Io.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:Jo.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof aa||this.isSocketShared)){this.socket.removeEventListener(ao.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new la("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new uo({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[un]||"destroying"===this[fn]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof wi&&!(e.detail instanceof So)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new aa;this.removeEventListener(ki.name,this.handleEventQUICSocket),this.dispatchEvent(new uo({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof wi&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new uo({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[ln]||"stopping"===this.socket[fn])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 ho(`${ho.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new uo({detail:new la("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Io.name,this.handleEventQUICConnectionError),t.removeEventListener(So.name,this.handleEventQUICConnectionSend),t.removeEventListener(ki.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}=Va();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[ln]&&(i=Ja(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(uo.name,this.handleEventQUICClientError),this.removeEventListener(fo.name,this.handleEventQUICClientClose),this.socket.removeEventListener(ao.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ki.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};ac([Dn(new na)],oc.prototype,"host",null),ac([Dn(new na)],oc.prototype,"port",null),ac([Dn(new na)],oc.prototype,"localHost",null),ac([Dn(new na)],oc.prototype,"localPort",null),ac([Po(!0,Ho,class extends ia{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,No)],oc,"createQUICClient",null),oc=ac([Nn({eventDestroy:class extends lo{},eventDestroyed:class extends lo{}})],oc);const cc=oc,lc=t(import.meta.url)("node:crypto");var dc=a.n(lc);class uc{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=uc.toUint8Array(e),s=uc.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 hc="string",fc=/^[0-9a-f\s]+$/i,gc=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,pc=/^[a-zA-Z0-9-_]+$/;class bc{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=uc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class mc{static toString(e,t=!1){const r=uc.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 yc{static isHex(e){return typeof e===hc&&fc.test(e)}static isBase64(e){return typeof e===hc&&gc.test(e)}static isBase64Url(e){return typeof e===hc&&pc.test(e)}static ToString(e,t="utf8"){const r=uc.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 mc.toString(r,!0);case"utf16":case"utf16be":return mc.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 mc.fromString(e,!0);case"utf16":case"utf16be":return mc.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=uc.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(!yc.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(!yc.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=yc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return bc.fromString(e);case"utf16":case"utf16be":return mc.fromString(e);case"utf16le":case"usc2":return mc.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=yc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return bc.toString(e);case"utf16":case"utf16be":return mc.toString(e);case"utf16le":case"usc2":return mc.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=uc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=uc.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(!yc.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 mc.toString(e,t)}static FromUtf16String(e,t=!1){return mc.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 Ac(...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 Ic(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 vc(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 wc(e,t,r=-1){const s=r;let i=e,n=0,a=Math.pow(2,t);for(let r=1;r<8;r++){if(e<a){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 a=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);a[n-e-1]=Math.floor(i/r),i-=a[n-e-1]*r}return e}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Sc(...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 Ec(){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=vc(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,vc(n,8)-s}function Cc(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 kc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function xc(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 _c(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)}yc.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Bc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xc(this.items)}}const Rc=[new Uint8Array([1])],Oc="0123456789",Uc="name",Tc="valueHexView",Nc="isHexOnly",Dc="idBlock",Mc="tagClass",Pc="tagNumber",Lc="isConstructed",Hc="fromBER",Vc="toBER",Kc="local",Qc="",Fc=new ArrayBuffer(0),$c=new Uint8Array(0),Gc="EndOfContent",jc="OCTET STRING",qc="BIT STRING";function zc(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?uc.toUint8Array(r.valueHex):$c}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!_c(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",Fc)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:yc.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Wc{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=Qc,warnings:r=[],valueBeforeDecode:s=$c}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=uc.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:yc.ToHex(this.valueBeforeDecodeView)}}}Wc.NAME="baseBlock";class Jc extends Wc{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'")}}Jc.NAME="valueBlock";class Yc extends(zc(Wc)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?uc.toUint8Array(e.valueHex):$c,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",Fc}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=wc(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=uc.toUint8Array(e);if(!_c(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=vc(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}}}Yc.NAME="identificationBlock";class Xc extends Wc{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=uc.toUint8Array(e);if(!_c(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 a=t+1,o=s.subarray(a,a+n);return 0===o[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=vc(o,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=wc(this.length,8);if(s.byteLength>127)return this.error="Too big length",Fc;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}}}Xc.NAME="lengthBlock";const Zc={};class el extends Wc{constructor({name:e=Qc,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Yc(s),this.lenBlock=new Xc(s),this.valueBlock=i?new i(s):new Jc(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 Bc;t||tl(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?Fc: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():yc.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${yc.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 tl(e){var t;if(e instanceof Zc.Constructed)for(const t of e.valueBlock.value)tl(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}el.NAME="BaseBlock";class rl extends el{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Qc,...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}'`}}rl.NAME="BaseStringBlock";class sl extends(zc(Jc)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var il,nl,al,ol,cl,ll,dl,ul,hl,fl,gl,pl,bl,ml,yl,Al,Il,vl,wl,Sl,El,Cl,kl,xl,_l,Bl,Rl,Ol,Ul,Tl,Nl,Dl,Ml,Pl,Ll,Hl;sl.NAME="PrimitiveValueBlock";class Vl extends el{constructor(e={}){super(e,sl),this.idBlock.isConstructed=!1}}function Kl(e,t=0,r=e.length){const s=t;let i=new el({},Jc);const n=new Wc;if(!_c(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 a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,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 o=el;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};o=Zc.EndOfContent;break;case 1:o=Zc.Boolean;break;case 2:o=Zc.Integer;break;case 3:o=Zc.BitString;break;case 4:o=Zc.OctetString;break;case 5:o=Zc.Null;break;case 6:o=Zc.ObjectIdentifier;break;case 10:o=Zc.Enumerated;break;case 12:o=Zc.Utf8String;break;case 13:o=Zc.RelativeObjectIdentifier;break;case 14:o=Zc.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:o=Zc.Sequence;break;case 17:o=Zc.Set;break;case 18:o=Zc.NumericString;break;case 19:o=Zc.PrintableString;break;case 20:o=Zc.TeletexString;break;case 21:o=Zc.VideotexString;break;case 22:o=Zc.IA5String;break;case 23:o=Zc.UTCTime;break;case 24:o=Zc.GeneralizedTime;break;case 25:o=Zc.GraphicString;break;case 26:o=Zc.VisibleString;break;case 27:o=Zc.GeneralString;break;case 28:o=Zc.UniversalString;break;case 29:o=Zc.CharacterString;break;case 30:o=Zc.BmpString;break;case 31:o=Zc.DATE;break;case 32:o=Zc.TimeOfDay;break;case 33:o=Zc.DateTime;break;case 34:o=Zc.Duration;break;default:{const e=i.idBlock.isConstructed?new Zc.Constructed:new Zc.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else o=i.idBlock.isConstructed?Zc.Constructed:Zc.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,o),a=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:a,result:i}}function Ql(e){if(!e.byteLength){const e=new el({},Jc);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Kl(uc.toUint8Array(e).slice(),0,e.byteLength)}function Fl(e,t){return e?1:t}il=Vl,Zc.Primitive=il,Vl.NAME="PRIMITIVE";class $l extends Jc{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=uc.toUint8Array(e);if(!_c(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(;Fl(this.isIndefiniteForm,r)>0;){const e=Kl(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===Gc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Bc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?Fc:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}$l.NAME="ConstructedValueBlock";class Gl extends el{constructor(e={}){super(e,$l),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} :`}}nl=Gl,Zc.Constructed=nl,Gl.NAME="CONSTRUCTED";class jl extends Jc{fromBER(e,t,r){return t}toBER(e){return Fc}}jl.override="EndOfContentValueBlock";class ql extends el{constructor(e={}){super(e,jl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}al=ql,Zc.EndOfContent=al,ql.NAME=Gc;class zl extends el{constructor(e={}){super(e,Jc),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}`}}ol=zl,Zc.Null=ol,zl.NAME="NULL";class Wl extends(zc(Jc)){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=uc.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=uc.toUint8Array(e);return _c(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,Ec.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Wl.NAME="BooleanValueBlock";class Jl extends el{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Wl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}cl=Jl,Zc.Boolean=cl,Jl.NAME="BOOLEAN";class Yl extends(zc($l)){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=$l.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===Gc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==jc)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?$l.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Yl.NAME="OctetStringValueBlock";class Xl extends el{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},Yl),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=Kl(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?Gl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${yc.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 ll&&e.push(t.valueBlock.valueHexView);return uc.concat(e)}}ll=Xl,Zc.OctetString=ll,Xl.NAME=jc;class Zl extends(zc($l)){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=$l.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===Gc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==qc)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=uc.toUint8Array(e);if(!_c(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=Kl(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 $l.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Fc;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}}}Zl.NAME="BitStringValueBlock";class ed extends el{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},Zl),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 Gl.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 td(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const a=n.length-1,o=i.slice(0),c=o.length-1;let l=0,d=0;for(let e=c<a?a:c;e>=0;e--,d++)l=1==d<o.length?n[a-d]+o[c-d]+r[0]:n[a-d]+r[0],r[0]=l/10,1==d>=n.length?n=Sc(new Uint8Array([l%10]),n):n[a-d]=l%10;return r[0]>0&&(n=Sc(r,n)),n}function rd(e){if(e>=Rc.length)for(let t=Rc.length;t<=e;t++){const e=new Uint8Array([0]);let r=Rc[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=Sc(e,r)),Rc.push(r)}return Rc[e]}function sd(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),a=n.length-1,o=i.slice(0),c=o.length-1;let l,d=0;for(let e=c;e>=0;e--,d++)l=n[a-d]-o[c-d]-r,1==l<0?(r=1,n[a-d]=l+10):(r=0,n[a-d]=l);if(r>0)for(let e=a-c+1;e>=0;e--,d++){if(l=n[a-d]-r,!(l<0)){r=0,n[a-d]=l;break}r=1,n[a-d]=l+10}return n.slice()}dl=ed,Zc.BitString=dl,ed.NAME=qc;class id extends(zc(Jc)){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=Ec.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=wc(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=wc(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="",a=!1;for(let a=i.byteLength-1;a>=0;a--){t=i[a];for(let i=0;i<8;i++)1&~t||(s===e?(r=sd(rd(s),r),n="-"):r=td(r,rd(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(a=!0),a&&(n+=Oc.charAt(r[e]));return!1===a&&(n+=Oc.charAt(0)),n}}ul=id,id.NAME="IntegerValueBlock",Object.defineProperty(ul.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class nd extends el{constructor(e={}){super(e,id),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return kc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){kc();const t=BigInt(e),r=new Bc,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(yc.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${yc.ToHex(e)}`)+t,n=uc.toUint8Array(yc.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new hl({valueHex:r.final()})}convertToDER(){const e=new hl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new hl({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}hl=nd,Zc.Integer=hl,nd.NAME="INTEGER";class ad extends nd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}fl=ad,Zc.Enumerated=fl,ad.NAME="ENUMERATED";class od extends(zc(Jc)){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=uc.toUint8Array(e);if(!_c(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=vc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){kc();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=wc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Fc;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=yc.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}}}od.NAME="sidBlock";class cd extends Jc{constructor({value:e=Qc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new od;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,Fc;t.push(s)}return xc(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 od;if(s>Number.MAX_SAFE_INTEGER){kc();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}}cd.NAME="ObjectIdentifierValueBlock";class ld extends el{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,cd),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}gl=ld,Zc.ObjectIdentifier=gl,ld.NAME="OBJECT IDENTIFIER";class dd extends(zc(Wc)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=uc.toUint8Array(e);if(!_c(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=vc(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=wc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Fc;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?yc.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}dd.NAME="relativeSidBlock";class ud extends Jc{constructor({value:e=Qc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new dd;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,Fc;r.push(s)}return xc(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 dd;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}}ud.NAME="RelativeObjectIdentifierValueBlock";class hd extends el{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ud),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}pl=hd,Zc.RelativeObjectIdentifier=pl,hd.NAME="RelativeObjectIdentifier";class fd extends Gl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}bl=fd,Zc.Sequence=bl,fd.NAME="SEQUENCE";class gd extends Gl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}ml=gd,Zc.Set=ml,gd.NAME="SET";class pd extends(zc(Jc)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Qc}toJSON(){return{...super.toJSON(),value:this.value}}}pd.NAME="StringValueBlock";class bd extends pd{}bd.NAME="SimpleStringValueBlock";class md extends rl{constructor({...e}={}){super(e,bd)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,uc.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}}md.NAME="SIMPLE STRING";class yd extends md{fromBuffer(e){this.valueBlock.valueHexView=uc.toUint8Array(e);try{this.valueBlock.value=yc.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=yc.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(yc.FromUtf8String(e)),this.valueBlock.value=e}}yd.NAME="Utf8StringValueBlock";class Ad extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}yl=Ad,Zc.Utf8String=yl,Ad.NAME="UTF8String";class Id extends md{fromBuffer(e){this.valueBlock.value=yc.ToUtf16String(e),this.valueBlock.valueHexView=uc.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(yc.FromUtf16String(e))}}Id.NAME="BmpStringValueBlock";class vd extends Id{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Al=vd,Zc.BmpString=Al,vd.NAME="BMPString";class wd extends md{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=wc(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}}wd.NAME="UniversalStringValueBlock";class Sd extends wd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Il=Sd,Zc.UniversalString=Il,Sd.NAME="UniversalString";class Ed extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}vl=Ed,Zc.NumericString=vl,Ed.NAME="NumericString";class Cd extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}wl=Cd,Zc.PrintableString=wl,Cd.NAME="PrintableString";class kd extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Sl=kd,Zc.TeletexString=Sl,kd.NAME="TeletexString";class xd extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}El=xd,Zc.VideotexString=El,xd.NAME="VideotexString";class _d extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Cl=_d,Zc.IA5String=Cl,_d.NAME="IA5String";class Bd extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}kl=Bd,Zc.GraphicString=kl,Bd.NAME="GraphicString";class Rd extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}xl=Rd,Zc.VisibleString=xl,Rd.NAME="VisibleString";class Od extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}_l=Od,Zc.GeneralString=_l,Od.NAME="GeneralString";class Ud extends md{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Bl=Ud,Zc.CharacterString=Bl,Ud.NAME="CharacterString";class Td extends Rd{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,uc.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]=Cc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Cc(this.month,2),e[2]=Cc(this.day,2),e[3]=Cc(this.hour,2),e[4]=Cc(this.minute,2),e[5]=Cc(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}}}Rl=Td,Zc.UTCTime=Rl,Td.NAME="UTCTime";class Nd extends Td{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,a=0,o=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(a=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");o=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)+a;break;case 5:this.minute=parseInt(l[e],10)+o;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(Cc(this.year,4)),e.push(Cc(this.month,2)),e.push(Cc(this.day,2)),e.push(Cc(this.hour,2)),e.push(Cc(this.minute,2)),e.push(Cc(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(Cc(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Ol=Nd,Zc.GeneralizedTime=Ol,Nd.NAME="GeneralizedTime";class Dd extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Ul=Dd,Zc.DATE=Ul,Dd.NAME="DATE";class Md extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Tl=Md,Zc.TimeOfDay=Tl,Md.NAME="TimeOfDay";class Pd extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Nl=Pd,Zc.DateTime=Nl,Pd.NAME="DateTime";class Ld extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Dl=Ld,Zc.Duration=Dl,Ld.NAME="Duration";class Hd extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ml=Hd,Zc.TIME=Ml,Hd.NAME="TIME";class Vd{constructor({name:e=Qc,optional:t=!1}={}){this.name=e,this.optional=t}}class Kd extends Vd{constructor({value:e=[],...t}={}){super(t),this.value=e}}class Qd extends Vd{constructor({value:e=new Vd,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class Fd{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=uc.toUint8Array(e)}constructor({data:e=$c}={}){this.dataView=uc.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=uc.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function $d(e,t,r){if(r instanceof Kd){for(const s of r.value)if($d(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Uc)&&(e.name=r.name),e}}if(r instanceof Vd)return r.hasOwnProperty(Uc)&&(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(Dc in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Hc in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Vc 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(Mc))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(Pc))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(Lc))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Nc 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(Tc 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,Qc),r.name&&(e[r.name]=t)),r instanceof Zc.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof Qd&&(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,Qc),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let a=0;a<n;a++)if(a-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[a].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,Qc),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof Qd){if(i=$d(e,t.valueBlock.value[a],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,Qc),r.name&&delete e[r.name]),i;s++}if(Uc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=Kc 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[a])}}else if(i=$d(e,t.valueBlock.value[a-s],r.valueBlock.value[a]),!1===i.verified){if(!r.valueBlock.value[a].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Qc),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,Qc),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&Tc in t.valueBlock){const s=Kl(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,Qc),r.name&&(delete e[r.name],t.name=r.name)),t}return $d(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function Gd(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=Kl(uc.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:$d(r.result,r.result,t)}(Hl=Pl||(Pl={}))[Hl.Sequence=0]="Sequence",Hl[Hl.Set=1]="Set",Hl[Hl.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"}(Ll||(Ll={}));class jd{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!uc.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=uc.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof ed))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 ed({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new ed({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 qd{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):uc.isBufferSource(e)?this.buffer=uc.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Xl))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Xl({valueHex:this.buffer})}toSchema(e){return new Xl({name:e})}}const zd={fromASN:e=>e instanceof zl?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new zl;const t=Ql(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Wd={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new nd({value:+e})},Jd={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new ad({value:e})},Yd={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new nd({valueHex:e})},Xd={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new ed({valueHex:e})},Zd={fromASN:e=>e.valueBlock.toString(),toASN:e=>new ld({value:e})},eu={fromASN:e=>e.valueBlock.value,toASN:e=>new Jl({value:e})},tu={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Xl({valueHex:e})},ru={fromASN:e=>new qd(e.getValue()),toASN:e=>e.toASN()};function su(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const iu=su(Ad),nu=su(vd),au=su(Sd),ou=su(Ed),cu=su(Cd),lu=su(kd),du=su(xd),uu=su(_d),hu=su(Bd),fu=su(Rd),gu=su(Od),pu=su(Ud),bu={fromASN:e=>e.toDate(),toASN:e=>new Td({valueDate:e})},mu={fromASN:e=>e.toDate(),toASN:e=>new Nd({valueDate:e})},yu={fromASN:()=>null,toASN:()=>new zl};function Au(e){switch(e){case Ll.Any:return zd;case Ll.BitString:return Xd;case Ll.BmpString:return nu;case Ll.Boolean:return eu;case Ll.CharacterString:return pu;case Ll.Enumerated:return Jd;case Ll.GeneralString:return gu;case Ll.GeneralizedTime:return mu;case Ll.GraphicString:return hu;case Ll.IA5String:return uu;case Ll.Integer:return Wd;case Ll.Null:return yu;case Ll.NumericString:return ou;case Ll.ObjectIdentifier:return Zd;case Ll.OctetString:return tu;case Ll.PrintableString:return cu;case Ll.TeletexString:return lu;case Ll.UTCTime:return bu;case Ll.UniversalString:return au;case Ll.Utf8String:return iu;case Ll.VideotexString:return du;case Ll.VisibleString:return fu;default:return null}}function Iu(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Iu(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function vu(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||vu(r)}return!1}function wu(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 Su=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:Pl.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 a;if("number"==typeof i.type){const e=Ll[i.type],t=o[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);a=new t({name:n})}else Iu(i.type)?a=(new i.type).toSchema(n):i.optional?this.get(i.type).type===Pl.Choice?a=new Vd({name:n}):(a=this.create(i.type,!1),a.name=n):a=new Vd({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(a.name="",a=new("set"===i.repeated?gd:fd)({name:"",value:[new Qd({name:n,value:a})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Iu(i.type)){const e=i.repeated?Gl:Vl;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?a:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new Gl({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new Gl({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,s.push(a)}switch(r.type){case Pl.Sequence:return new fd({value:s,name:""});case Pl.Set:return new gd({value:s,name:""});case Pl.Choice:return new Kd({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}},Eu=e=>t=>{let r;Su.has(t)?r=Su.get(t):(r=Su.createDefault(t),Su.set(t,r)),Object.assign(r,e)},Cu=e=>(t,r)=>{let s;Su.has(t.constructor)?s=Su.get(t.constructor):(s=Su.createDefault(t.constructor),Su.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Au(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 ku extends Error{constructor(){super(...arguments),this.schemas=[]}}class xu{static parse(e,t){const r=Ql(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(Iu(t))return(new t).fromASN(e);const s=Su.get(t);Su.cache(t);let i=s.schema;if(e.constructor===Gl&&s.type!==Pl.Choice){i=new Gl({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=$d({},e,i);if(!n.verified)throw new ku(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const a=new t;if(vu(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=Au(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||Iu(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Iu(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?fd:gd);r.valueBlock=t.valueBlock;const n=Ql(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 o=n.result.valueBlock.value;a[e]=Array.from(o,e=>s.fromASN(e))}else a[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(Iu(c))e=(new c).toSchema("");else{const t=Ll[c],r=o[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=Ql(e.toBER(!1)).result}a[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.");a[e]=Array.from(t,e=>this.fromASN(e,c))}else a[e]=this.fromASN(t,c)}return a}catch(e){throw e instanceof ku&&e.schemas.push(t.name),e}}}class _u{static serialize(e){return e instanceof el?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Iu(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=Su.get(t);Su.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=Au(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],a=e[s];if(void 0===a||n.defaultValue===a||"object"==typeof n.defaultValue&&"object"==typeof a&&wu(this.serialize(n.defaultValue),this.serialize(a)))continue;const o=_u.toAsnItem(n,s,t,a);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Iu(n.type))i.push(new Gl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:o.valueBlock.value}));else{const e={};e.valueHex=o instanceof zl?o.valueBeforeDecodeView:o.valueBlock.toBER(),i.push(new Vl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Gl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[o]}));else n.repeated?i=i.concat(o):i.push(o)}switch(r.type){case Pl.Sequence:s=new fd({value:i});break;case Pl.Set:s=new gd({value:i});break;case Pl.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 ${Ll[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?fd:gd)({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?fd:gd)({value:t})}else i=this.toASN(s);return i}}class Bu extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Ru{static serialize(e){return _u.serialize(e)}static parse(e,t){return xu.parse(e,t)}static toString(e){const t=Ql(uc.isBufferSource(e)?uc.toArrayBuffer(e):Ru.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Ou(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class Uu extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class Tu extends Uu{constructor(e,t,r){super(t,r),this.schema=e}}class Nu extends Tu{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class Du extends Uu{}class Mu extends Uu{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class Pu extends Nu{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var Lu;function Hu(e,t){if(!function(e,t){switch(t){case Lu.Boolean:return"boolean"==typeof e;case Lu.Number:return"number"==typeof e;case Lu.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${Lu[t]}`)}function Vu(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||Vu(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"}(Lu||(Lu={}));const Ku="default",Qu=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 Fu{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 Du("Incoming value must be string");if(!t.exec(e))throw new Du(`Value doesn't match to pattern '${t.toString()}'`)}}class $u{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Hu(e,Lu.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 Du(`Value doesn't match to diapason [${e},${t}]`)}}}class Gu{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Hu(e,Lu.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 Du(`Value doesn't match to diapason (${e},${t})`)}}}class ju{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 Du(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new Du(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new Du(`Value length must be exactly ${this.length}.`)}}class qu{constructor(e){this.enumeration=e}validate(e){if(Hu(e,Lu.String),!this.enumeration.includes(e))throw new Du(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class zu{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof ju&&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)Hu(e,t.type)}}static getSchemaByName(e,t=Ku){return{...e.names[Ku],...e.names[t]}}}class Wu extends zu{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||Ku;if(Vu(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&&!Qu.has(s))throw new Uu("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,Qu.has(s)){const t=Qu.get(s);r={};const n=this.getSchemaByName(t,i);for(const a in n)try{const t=n[a],o=e[a];let c;if(t.optional&&void 0===o||void 0!==t.defaultValue&&o===t.defaultValue)continue;if(!t.optional&&void 0===o)throw new Mu(s.name,`Property '${a}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?o.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(o,e):o:t.repeated?o.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(o,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||a]=c}catch(e){throw e instanceof Mu?e:new Mu(t.target.name,`Property '${a}' 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 Ju extends zu{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||Ku,i=new r;if(Vu(i))return i.fromJSON(e);const n=Qu.get(r),a=this.getSchemaByName(n,s),o={};t.strictProperty&&!Array.isArray(e)&&Ju.checkStrictProperty(e,a,n);for(const r in a)try{const o=a[r],c=o.name||r,l=e[c];if(void 0===l&&(o.optional||void 0!==o.defaultValue))continue;if(!o.optional&&void 0===l)throw new Nu(n,`Property '${c}' is required.`);if(this.checkTypes(l,o),this.checkValues(l,o),"number"==typeof o.type)o.converter?o.repeated?i[r]=l.map(e=>o.converter.fromJSON(e,i)):i[r]=o.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:o.type,schemaName:s};o.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof Nu||(e=new Nu(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;o[r]=e}const c=Object.keys(o);if(c.length)throw new Pu(n,c,o);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 Pu(r,n)}}const Yu=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;Qu.has(t.constructor)?(i=Qu.get(t.constructor),i.target!==t.constructor&&(i=Qu.create(t.constructor),Qu.set(t.constructor,i))):(i=Qu.create(t.constructor),Qu.set(t.constructor,i));const n={type:Lu.Any,validations:[]},a=Object.assign(n,e);if(a.validations=function(e){const t=[];return e.pattern&&t.push(new Fu(e.pattern)),e.type!==Lu.Number&&e.type!==Lu.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new $u(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new Gu(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new qu(e.enumeration))),(e.type===Lu.String||e.repeated||e.type===Lu.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new ju(e.length,e.minLength,e.maxLength))),t}(a),"number"!=typeof a.type&&!Qu.has(a.type)&&!Vu(a.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let o;o=Array.isArray(e.schema)?e.schema:[e.schema||Ku];for(const e of o)i.names[e]||(i.names[e]={}),i.names[e][r]=a};class Xu extends Error{}class Zu extends Xu{}class eh extends Xu{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class th extends Xu{}class rh extends Xu{constructor(e){super(`${e}: Missing required property`)}}class sh{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return yc.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=yc.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 a=t.toUpperCase();return`-----BEGIN ${a}-----\n${n.join("\n")}\n-----END ${a}-----`}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 ih{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 eh("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 eh("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 eh("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 eh("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 eh("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 eh("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 th("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new eh("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 Xu("key: Is not extractable")}async onExportKey(e,t,...r){throw new eh("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 eh("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new Zu("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 Xu("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new rh(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new th(`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(!uc.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return uc.toArrayBuffer(e)}}class nh extends ih{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 ah extends nh{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 oh extends nh{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 th("length: Must be more than 0")}}class ch extends nh{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 th("length: Must be more than 0")}}class lh extends nh{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class dh extends nh{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 th("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 th("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class uh extends nh{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class hh extends ih{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 th(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class fh extends ih{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=yc.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 gh extends fh{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class ph extends fh{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 bh extends fh{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 mh extends ih{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 th(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class yh extends mh{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 Ah=["secret","private","public"];class Ih{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!==Ah.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class vh extends mh{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 Ih))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new th("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new th(`public: Is not ${this.name} key`)}}class wh extends vh{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class Sh extends mh{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Eh=class{constructor(e){e&&(this.value=e)}};Ou([Cu({type:Ll.ObjectIdentifier})],Eh.prototype,"value",void 0),Eh=Ou([Eu({type:Pl.Choice})],Eh);class Ch{constructor(e){Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Ch.prototype,"algorithm",void 0),Ou([Cu({type:Ll.Any,optional:!0})],Ch.prototype,"parameters",void 0);class kh{constructor(){this.version=0,this.privateKeyAlgorithm=new Ch,this.privateKey=new ArrayBuffer(0)}}Ou([Cu({type:Ll.Integer})],kh.prototype,"version",void 0),Ou([Cu({type:Ch})],kh.prototype,"privateKeyAlgorithm",void 0),Ou([Cu({type:Ll.OctetString})],kh.prototype,"privateKey",void 0),Ou([Cu({type:Ll.Any,optional:!0})],kh.prototype,"attributes",void 0);class xh{constructor(){this.publicKeyAlgorithm=new Ch,this.publicKey=new ArrayBuffer(0)}}Ou([Cu({type:Ch})],xh.prototype,"publicKeyAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],xh.prototype,"publicKey",void 0);const _h={fromJSON:e=>yc.FromBase64Url(e),toJSON:e=>yc.ToBase64Url(new Uint8Array(e))},Bh={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?Ac(new Uint8Array([0]).buffer,e):e;return new nd({valueHex:t})}};class Rh{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)}}Ou([Cu({type:Ll.Integer,converter:Wd})],Rh.prototype,"version",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"n",converter:_h})],Rh.prototype,"modulus",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"e",converter:_h})],Rh.prototype,"publicExponent",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"d",converter:_h})],Rh.prototype,"privateExponent",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"p",converter:_h})],Rh.prototype,"prime1",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"q",converter:_h})],Rh.prototype,"prime2",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"dp",converter:_h})],Rh.prototype,"exponent1",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"dq",converter:_h})],Rh.prototype,"exponent2",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"qi",converter:_h})],Rh.prototype,"coefficient",void 0),Ou([Cu({type:Ll.Any,optional:!0})],Rh.prototype,"otherPrimeInfos",void 0);class Oh{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"n",converter:_h})],Oh.prototype,"modulus",void 0),Ou([Cu({type:Ll.Integer,converter:Bh}),Yu({name:"e",converter:_h})],Oh.prototype,"publicExponent",void 0);let Uh=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 Xu("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:yc.ToBase64Url(e.buffer.slice(0,0+t)),y:yc.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=yc.FromBase64Url(e.x),r=yc.FromBase64Url(e.y),s=Ac(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Ou([Cu({type:Ll.OctetString})],Uh.prototype,"value",void 0),Uh=Ou([Eu({type:Pl.Choice})],Uh);class Th{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=yc.FromBase64Url(e.d),"x"in e){const t=new Uh;t.fromJSON(e);const r=_u.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=yc.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new Uh(this.publicKey).toJSON()),e}}Ou([Cu({type:Ll.Integer,converter:Wd})],Th.prototype,"version",void 0),Ou([Cu({type:Ll.OctetString})],Th.prototype,"privateKey",void 0),Ou([Cu({context:0,type:Ll.Any,optional:!0})],Th.prototype,"parameters",void 0),Ou([Cu({context:1,type:Ll.BitString,optional:!0})],Th.prototype,"publicKey",void 0);const Nh={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 nd({valueHex:e.buffer})}return new nd({valueHex:e})}};var Dh=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:Nh});class Mh{static decodePoint(e,t){const r=uc.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=uc.toUint8Array(e.x),i=uc.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=uc.toUint8Array(e.r),i=uc.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=uc.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 Ph{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=Mh.decodeSignature(e,8*t),s=new Ph;return s.r=uc.toArrayBuffer(r.r),s.s=uc.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 Mh.encodeSignature(this,e).buffer}}Ou([Cu({type:Ll.Integer,converter:Nh})],Ph.prototype,"r",void 0),Ou([Cu({type:Ll.Integer,converter:Nh})],Ph.prototype,"s",void 0);class Lh extends kh{}Ou([Cu({context:1,implicit:!0,type:Ll.BitString,optional:!0})],Lh.prototype,"publicKey",void 0);let Hh=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=yc.FromBase64Url(e.d),this}toJSON(){return{d:yc.ToBase64Url(this.value)}}};Ou([Cu({type:Ll.OctetString})],Hh.prototype,"value",void 0),Hh=Ou([Eu({type:Pl.Choice})],Hh);let Vh=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:yc.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=yc.FromBase64Url(e.x),this}};Ou([Cu({type:Ll.BitString})],Vh.prototype,"value",void 0),Vh=Ou([Eu({type:Pl.Choice})],Vh);let Kh=class{};Ou([Cu({type:Ll.OctetString}),Yu({type:Lu.String,converter:_h})],Kh.prototype,"d",void 0),Kh=Ou([Eu({type:Pl.Choice})],Kh);const Qh="1.2.840.10045.3.1.7",Fh="1.3.132.0",$h=`${Fh}.34`,Gh=`${Fh}.35`,jh=`${Fh}.10`,qh="1.3.36.3.3.2.8.1.1",zh=`${qh}.1`,Wh=`${qh}.2`,Jh=`${qh}.3`,Yh=`${qh}.4`,Xh=`${qh}.5`,Zh=`${qh}.6`,ef=`${qh}.7`,tf=`${qh}.8`,rf=`${qh}.9`,sf=`${qh}.10`,nf=`${qh}.11`,af=`${qh}.12`,of=`${qh}.13`,cf=`${qh}.14`;var lf=Object.freeze({__proto__:null,AlgorithmIdentifier:Ch,get CurvePrivateKey(){return Kh},EcDsaSignature:Ph,EcPrivateKey:Th,get EcPublicKey(){return Uh},get EdPrivateKey(){return Hh},get EdPublicKey(){return Vh},get ObjectIdentifier(){return Eh},OneAsymmetricKey:Lh,PrivateKeyInfo:kh,PublicKeyInfo:xh,RsaPrivateKey:Rh,RsaPublicKey:Oh,converters:Dh,idBrainpoolP160r1:zh,idBrainpoolP160t1:Wh,idBrainpoolP192r1:Jh,idBrainpoolP192t1:Yh,idBrainpoolP224r1:Xh,idBrainpoolP224t1:Zh,idBrainpoolP256r1:ef,idBrainpoolP256t1:tf,idBrainpoolP320r1:rf,idBrainpoolP320t1:sf,idBrainpoolP384r1:nf,idBrainpoolP384t1:af,idBrainpoolP512r1:of,idBrainpoolP512t1:cf,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:Fh,idSecp256k1:jh,idSecp256r1:Qh,idSecp384r1:$h,idSecp521r1:Gh,idVersionOne:qh,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class df{constructor(){}static register(e){const t=new Eh;t.value=e.id;const r=Ru.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}}df.items=[],df.names=[],df.register({name:"P-256",id:Qh,size:256}),df.register({name:"P-384",id:$h,size:384}),df.register({name:"P-521",id:Gh,size:521}),df.register({name:"K-256",id:jh,size:256}),df.register({name:"brainpoolP160r1",id:zh,size:160}),df.register({name:"brainpoolP160t1",id:Wh,size:160}),df.register({name:"brainpoolP192r1",id:Jh,size:192}),df.register({name:"brainpoolP192t1",id:Yh,size:192}),df.register({name:"brainpoolP224r1",id:Xh,size:224}),df.register({name:"brainpoolP224t1",id:Zh,size:224}),df.register({name:"brainpoolP256r1",id:ef,size:256}),df.register({name:"brainpoolP256t1",id:tf,size:256}),df.register({name:"brainpoolP320r1",id:rf,size:320}),df.register({name:"brainpoolP320t1",id:sf,size:320}),df.register({name:"brainpoolP384r1",id:nf,size:384}),df.register({name:"brainpoolP384t1",id:af,size:384}),df.register({name:"brainpoolP512r1",id:of,size:512}),df.register({name:"brainpoolP512t1",id:cf,size:512});class uf extends ih{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class hf extends ih{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class ff extends ih{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 gf extends ih{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 pf extends ih{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"),!uc.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!uc.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 bf extends ih{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 mf extends bf{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class yf extends bf{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class Af{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=yc.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class If{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 vf={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},wf=["pkcs8","spki","raw"];class Sf{constructor(){this.providers=new If}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=uc.toArrayBuffer(r),a=this.getProvider(i.name);return await a.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),a=this.getProvider(n.name);return await a.generateKey({...n,name:a.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),a=uc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.sign({...n,name:o.name},r,a,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const a=this.prepareAlgorithm(t),o=uc.toArrayBuffer(i),c=uc.toArrayBuffer(s),l=this.getProvider(a.name);return await l.verify({...a,name:l.name},r,c,o,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),a=uc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.encrypt({...n,name:o.name},r,a,{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),a=uc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.decrypt({...n,name:o.name},r,a,{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),a=this.getProvider(n.name);return await a.deriveBits({...n,name:a.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...a]=e,o=this.prepareAlgorithm(s);this.getProvider(o.name).checkDerivedKeyParams(o);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const d=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...a);return this.importKey("raw",d,s,i,n,...a)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!vf[t])throw new TypeError("Invalid keyFormat argument");if(!vf[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,...a]=e,o=this.prepareAlgorithm(s),c=this.getProvider(o.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!wf.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!uc.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...o,name:c.name},i,n,...a)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=yc.FromUtf8String(e)}const a=this.prepareAlgorithm(s),o=uc.toArrayBuffer(n),c=this.getProvider(a.name);return c.encrypt({...a,name:c.name},r,o,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,a,...o){const c=this.prepareAlgorithm(s),l=uc.toArrayBuffer(t),d=this.getProvider(c.name);let u=await d.decrypt({...c,name:d.name},r,l,{keyUsage:!1},...o);if("jwk"===e)try{u=JSON.parse(yc.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,a,...o)}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(Sf.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 Zu("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Ih))throw new TypeError("Key is not of type 'CryptoKey'")}}const Ef=t(import.meta.url)("buffer"),Cf=t(import.meta.url)("crypto");var kf=a.n(Cf);const xf=t(import.meta.url)("process"),_f={fromJSON:e=>Ef.Buffer.from(yc.FromBase64Url(e)),toJSON:e=>yc.ToBase64Url(e)};class Bf extends Ih{constructor(){super(...arguments),this.data=Ef.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Ou([Yu({name:"ext",type:Lu.Boolean,optional:!0})],Bf.prototype,"extractable",void 0),Ou([Yu({name:"key_ops",type:Lu.String,repeated:!0,optional:!0})],Bf.prototype,"usages",void 0),Ou([Yu({type:Lu.String})],Bf.prototype,"kty",void 0),Ou([Yu({type:Lu.String,optional:!0})],Bf.prototype,"alg",void 0);class Rf extends Bf{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class Of extends Bf{}class Uf extends Rf{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 Zu("Unsupported algorithm name")}}set alg(e){}}Ou([Yu({name:"k",converter:_f})],Uf.prototype,"data",void 0);class Tf{static async generateKey(e,t,r){const s=new Uf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=kf().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof Uf))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return Wu.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new th("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Ju.fromJSON(t,{targetSchema:Uf});break;case"raw":n=new Uf,n.data=Ef.Buffer.from(t);break;default:throw new th("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 th("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,Ef.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,Ef.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,Ef.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,Ef.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,Ef.Buffer.from(r));default:throw new th("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Uf))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,Ef.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,Ef.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,Ef.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,Ef.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,Ef.Buffer.from(r));default:throw new th("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=kf().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=kf().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=kf().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,Ef.Buffer.from(e.counter));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=kf().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=kf().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,Ef.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(Ef.Buffer.from(e.additionalData));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=kf().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),a=r.slice(r.length-s);e.additionalData&&i.setAAD(Ef.Buffer.from(e.additionalData)),i.setAuthTag(a);let o=i.update(n);return o=Ef.Buffer.concat([o,i.final()]),new Uint8Array(o).buffer}static async encryptAesKW(e,t,r){const s=kf().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=kf().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=kf().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=kf().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}Tf.AES_KW_IV=Ef.Buffer.from("A6A6A6A6A6A6A6A6","hex");const Nf=new WeakMap;function Df(e){const t=Nf.get(e);if(!t)throw new th("Cannot get CryptoKey from secure storage");return t}function Mf(e){const t=Ih.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),Nf.set(t,e),t}class Pf extends ah{async onGenerateKey(e,t,r){return Mf(await Tf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Tf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Tf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}const Lf=Ef.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Hf=Ef.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),Vf=16;function Kf(e){const t=Ef.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 Qf(e,t){const r=Math.min(e.length,t.length),s=Ef.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function Ff(e,t){const r=kf().createCipheriv("aes"+(e.length<<3),e,Lf),s=r.update(t);return r.final(),s}function $f(e,t){const r=Ef.Buffer.alloc(Vf),s=t*Vf,i=s+Vf;return e.copy(r,0,s,i),r}class Gf extends oh{async onGenerateKey(e,t,r){return Mf(await Tf.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=Ff(e,Lf);let r=Kf(t);128&t[0]&&(r=Qf(r,Hf));let s=Kf(r);return 128&r[0]&&(s=Qf(s,Hf)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/Vf);0===n?(n=1,s=!1):s=t.length%Vf===0;const a=n-1;i=s?Qf($f(t,a),r.subkey1):Qf(function(e,t){const r=Ef.Buffer.alloc(Vf),s=t*Vf,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,a),r.subkey2);let o,c=Lf;for(let r=0;r<a;r++)o=Qf(c,$f(t,r)),c=Ff(e,o);return o=Qf(i,c),Ff(e,o)}(Df(t).data,Ef.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===Ef.Buffer.from(r).compare(Ef.Buffer.from(i))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}class jf extends ch{async onGenerateKey(e,t,r){return Mf(await Tf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Tf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Tf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}class qf extends dh{async onGenerateKey(e,t,r){return Mf(await Tf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Tf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Tf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}class zf extends uh{async onGenerateKey(e,t,r){return Mf(await Tf.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return Tf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Tf.decrypt(e,Df(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}class Wf extends lh{async onGenerateKey(e,t,r){return Mf(await Tf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Tf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Tf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Tf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Tf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Uf))throw new TypeError("key: Is not a AesCryptoKey")}}class Jf extends Rf{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new Zu("Unsupported algorithm name")}}set alg(e){}}Ou([Yu({name:"k",converter:_f})],Jf.prototype,"data",void 0);class Yf{static async generateKey(e,t,r){const s=new Jf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=kf().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Wu.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new th("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Ju.fromJSON(t,{targetSchema:Jf});break;case"raw":n=new Jf,n.data=Ef.Buffer.from(t);break;default:throw new th("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,Ef.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,Ef.Buffer.from(r));default:throw new th("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Jf))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,Ef.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,Ef.Buffer.from(r));default:throw new th("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=kf().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=kf().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=kf().createCipheriv("des-ede3-cbc",t.data,Ef.Buffer.from(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=kf().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Ef.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class Xf extends hh{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return Mf(await Yf.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return Yf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Yf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Yf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){const n=await Yf.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new th("keyData: Wrong key size");return Mf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Jf))throw new TypeError("key: Is not a DesCryptoKey")}}class Zf extends hh{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return Mf(await Yf.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return Yf.encrypt(e,Df(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Yf.decrypt(e,Df(t),new Uint8Array(r))}async onExportKey(e,t){return Yf.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){const n=await Yf.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new th("keyData: Wrong key size");return Mf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Jf))throw new TypeError("key: Is not a DesCryptoKey")}}function eg(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 th("algorithm: Is not recognized")}}class tg extends Of{constructor(){super(...arguments),this.type="private"}getKey(){const e=xu.parse(this.data,lf.PrivateKeyInfo);return xu.parse(e.privateKey,lf.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:eg(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Wu.toJSON(e))}fromJSON(e){const t=Ju.fromJSON(e,{targetSchema:lf.RsaPrivateKey}),r=new lf.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=_u.serialize(t),this.data=Ef.Buffer.from(_u.serialize(r))}}class rg extends Of{constructor(){super(...arguments),this.type="public"}getKey(){const e=xu.parse(this.data,lf.PublicKeyInfo);return xu.parse(e.publicKey,lf.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:eg(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Wu.toJSON(e))}fromJSON(e){const t=Ju.fromJSON(e,{targetSchema:lf.RsaPublicKey}),r=new lf.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=_u.serialize(t),this.data=Ef.Buffer.from(_u.serialize(r))}}class sg{static async generateKey(e,t,r){const s=new tg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new rg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=Ef.Buffer.concat([Ef.Buffer.alloc(4-e.publicExponent.byteLength,0),Ef.Buffer.from(e.publicExponent)]).readInt32BE(0),a=kf().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Wu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new th("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=Ju.fromJSON(t,{targetSchema:lf.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Ju.fromJSON(t,{targetSchema:lf.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=xu.parse(new Uint8Array(t),lf.PublicKeyInfo),n=xu.parse(e.publicKey,lf.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=xu.parse(new Uint8Array(t),lf.PrivateKeyInfo),n=xu.parse(e.privateKey,lf.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new th("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 th("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 th("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new th("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new th("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new lf.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=_u.serialize(e);const n=new tg;return n.data=Ef.Buffer.from(_u.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 lf.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=_u.serialize(e);const n=new rg;return n.data=Ef.Buffer.from(_u.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 th("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=kf().createSign(s);i.update(Ef.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=kf().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const a=i.sign(n);return new Uint8Array(a).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=kf().createVerify(i);n.update(Ef.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(a.padding=kf().constants.RSA_PKCS1_PSS_PADDING,a.saltLength=e.saltLength),n.verify(a,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:kf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(kf().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:kf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(kf().privateDecrypt(s,r)).buffer}}sg.publicKeyUsages=["verify","encrypt","wrapKey"],sg.privateKeyUsages=["sign","decrypt","unwrapKey"];class ig extends gh{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 sg.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onSign(e,t,r){return sg.sign(e,Df(t),new Uint8Array(r))}async onVerify(e,t,r,s){return sg.verify(e,Df(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return sg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await sg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof tg||r instanceof rg))throw new TypeError("key: Is not RSA CryptoKey")}}class ng extends ph{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 sg.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onSign(e,t,r){return sg.sign(e,Df(t),new Uint8Array(r))}async onVerify(e,t,r,s){return sg.verify(e,Df(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return sg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await sg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof tg||r instanceof rg))throw new TypeError("key: Is not RSA CryptoKey")}}class ag{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=kf().createHash(r).update(Ef.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class og extends bh{async onGenerateKey(e,t,r){const s=await sg.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onEncrypt(e,t,r){const s=Df(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),a=ag.size(s.algorithm.hash)>>3,o=i.byteLength,c=n-o-2*a-2;if(o>n-2*a-2)throw new Error("Data too large");const l=new Uint8Array(n),d=l.subarray(1,a+1),u=l.subarray(a+1);u.set(i,a+c+1);const h=kf().createHash(s.algorithm.hash.name.replace("-","")).update(uc.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(h,0),u[a+c]=1,kf().randomFillSync(d);const f=this.mgf1(s.algorithm.hash,d,u.length);for(let e=0;e<u.length;e++)u[e]^=f[e];const g=this.mgf1(s.algorithm.hash,u,d.length);for(let e=0;e<d.length;e++)d[e]^=g[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=kf().publicEncrypt({key:s.pem,padding:kf().constants.RSA_NO_PADDING},Ef.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=Df(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=ag.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 a=kf().privateDecrypt({key:s.pem,padding:kf().constants.RSA_NO_PADDING},Ef.Buffer.from(r));const o=a[0],c=a.subarray(1,n+1),l=a.subarray(n+1);if(0!==o)throw new Error("Decryption failed");const d=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=d[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const h=kf().createHash(s.algorithm.hash.name.replace("-","")).update(uc.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(h[e]!==l[e])throw new Error("Decryption failed");let f=n;for(;f<l.length;f++){const e=l[f];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(f===l.length)throw new Error("Decryption failed");return a=l.subarray(f+1),new Uint8Array(a).buffer}async onExportKey(e,t){return sg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await sg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof tg||r instanceof rg))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=ag.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),a=Math.ceil(r/s);for(let r=0;r<a;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const a=i.subarray(r*s);let o=kf().createHash(e.name.replace("-","")).update(t).update(n).digest();o.length>a.length&&(o=o.subarray(0,a.length)),a.set(o)}return i}}class cg extends ih{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 sg.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(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=yc.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=kf().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=kf().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return sg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await sg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof tg||r instanceof rg))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${Df(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:kf().constants.RSA_PKCS1_PADDING}}}const lg={"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 dg(e){const t=lg[e];if(!t)throw new th(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class ug extends Of{constructor(){super(...arguments),this.type="private"}getKey(){const e=xu.parse(this.data,lf.PrivateKeyInfo);return xu.parse(e.privateKey,lf.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Wu.toJSON(e))}fromJSON(e){if(!e.crv)throw new th("Cannot get named curve from JWK. Property 'crv' is required");const t=new lf.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=_u.serialize(new lf.ObjectIdentifier(dg(e.crv)));const r=Ju.fromJSON(e,{targetSchema:lf.EcPrivateKey});return t.privateKey=_u.serialize(r),this.data=Ef.Buffer.from(_u.serialize(t)),this}}class hg extends Of{constructor(){super(...arguments),this.type="public"}getKey(){const e=xu.parse(this.data,lf.PublicKeyInfo);return new lf.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,Wu.toJSON(e))}fromJSON(e){if(!e.crv)throw new th("Cannot get named curve from JWK. Property 'crv' is required");const t=Ju.fromJSON(e,{targetSchema:lf.EcPublicKey}),r=new lf.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=_u.serialize(new lf.ObjectIdentifier(dg(e.crv))),r.publicKey=_u.toASN(t).valueHex,this.data=Ef.Buffer.from(_u.serialize(r)),this}}class fg extends ih{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class gg extends ih{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class pg extends ih{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class bg extends ih{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class mg extends ih{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class yg extends ih{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class Ag extends ih{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return ag.digest(e,t)}}class Ig{static async generateKey(e,t,r){const s=new ug;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new hg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=kf().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=ag.getAlgorithmName(e.hash),i=kf().createSign(s);i.update(Ef.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},a=i.sign(n),o=xu.parse(a,lf.EcDsaSignature);return Mh.encodeSignature(o,df.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=ag.getAlgorithmName(e.hash),n=kf().createVerify(i);n.update(Ef.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem},o=new lf.EcDsaSignature,c=df.get(t.algorithm.namedCurve),l=Mh.decodeSignature(r,c.size);o.r=uc.toArrayBuffer(l.r),o.s=uc.toArrayBuffer(l.s);const d=Ef.Buffer.from(_u.serialize(o));return n.verify(a,d)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=kf().createECDH(s),n=xu.parse(t.data,lf.PrivateKeyInfo),a=xu.parse(n.privateKey,lf.EcPrivateKey);i.setPrivateKey(Ef.Buffer.from(a.privateKey));const o=xu.parse(e.public.data,lf.PublicKeyInfo),c=i.computeSecret(Ef.Buffer.from(o.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Wu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return xu.parse(t.data,lf.PublicKeyInfo).publicKey;default:throw new th("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=Ju.fromJSON(t,{targetSchema:lf.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Ju.fromJSON(t,{targetSchema:lf.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new lf.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=xu.parse(new Uint8Array(t),lf.PublicKeyInfo),n=new lf.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=xu.parse(new Uint8Array(t),lf.PrivateKeyInfo),n=xu.parse(e.privateKey,lf.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new th("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Xu("Key info doesn't have required parameters");let r="";try{r=xu.parse(e,lf.ObjectIdentifier).value}catch(e){throw new Xu("Cannot read key info parameters")}if(dg(t)!==r)throw new Xu("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new lf.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=_u.serialize(new lf.ObjectIdentifier(dg(t.namedCurve))),i.privateKey=_u.serialize(e);const n=new ug;return n.data=Ef.Buffer.from(_u.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new lf.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=dg(t.namedCurve);i.publicKeyAlgorithm.parameters=_u.serialize(new lf.ObjectIdentifier(n)),i.publicKey=e.value;const a=new hg;return a.data=Ef.Buffer.from(_u.serialize(i)),a.algorithm=Object.assign({},t),a.extractable=r,a.usages=s,a}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}}}Ig.publicKeyUsages=["verify"],Ig.privateKeyUsages=["sign","deriveKey","deriveBits"];class vg extends yh{constructor(){super(...arguments),this.namedCurves=df.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 Ig.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onSign(e,t,r){return Ig.sign(e,Df(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Ig.verify(e,Df(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Ig.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof ug||r instanceof hg))throw new TypeError("key: Is not EC CryptoKey")}}class wg extends vh{constructor(){super(...arguments),this.namedCurves=df.names}async onGenerateKey(e,t,r){const s=await Ig.generateKey({...e,name:this.name},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onExportKey(e,t){return Ig.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await Ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Df(e);if(!(r instanceof ug||r instanceof hg))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await Ig.deriveBits({...e,public:Df(e.public)},Df(t),r)}}const Sg={[lf.idEd448]:"Ed448",ed448:lf.idEd448,[lf.idX448]:"X448",x448:lf.idX448,[lf.idEd25519]:"Ed25519",ed25519:lf.idEd25519,[lf.idX25519]:"X25519",x25519:lf.idX25519};function Eg(e){const t=Sg[e.toLowerCase()];if(!t)throw new th(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class Cg extends Of{constructor(){super(...arguments),this.type="private"}getKey(){const e=xu.parse(this.data,lf.PrivateKeyInfo);return xu.parse(e.privateKey,lf.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Wu.toJSON(e))}fromJSON(e){if(!e.crv)throw new th("Cannot get named curve from JWK. Property 'crv' is required");const t=new lf.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=Eg(e.crv);const r=Ju.fromJSON(e,{targetSchema:lf.CurvePrivateKey});return t.privateKey=_u.serialize(r),this.data=Ef.Buffer.from(_u.serialize(t)),this}}class kg extends Of{constructor(){super(...arguments),this.type="public"}getKey(){return xu.parse(this.data,lf.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:yc.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new th("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new th("Cannot get property from JWK. Property 'x' is required");const t=new lf.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=Eg(e.crv),t.publicKey=yc.FromBase64Url(e.x),this.data=Ef.Buffer.from(_u.serialize(t)),this}}class xg{static async generateKey(e,t,r){const s=new Cg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new kg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),a=kf().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.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=kf().sign(null,Ef.Buffer.from(r),s);return uc.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 kf().verify(null,Ef.Buffer.from(s),i,Ef.Buffer.from(r))}static async deriveBits(e,t,r){const s=kf().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=kf().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=kf().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 Wu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return xu.parse(t.data,lf.PublicKeyInfo).publicKey;default:throw new th("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=Ju.fromJSON(t,{targetSchema:lf.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(yc.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=xu.parse(new Uint8Array(t),lf.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=xu.parse(new Uint8Array(t),lf.PrivateKeyInfo),n=xu.parse(e.privateKey,lf.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new th("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new Cg;return i.fromJSON({crv:t.namedCurve,d:yc.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 kg;return i.fromJSON({crv:t.namedCurve,x:yc.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}xg.publicKeyUsages=["verify"],xg.privateKeyUsages=["sign","deriveKey","deriveBits"];class _g extends Sh{async onGenerateKey(e,t,r){const s=await xg.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onSign(e,t,r){return xg.sign(e,Df(t),new Uint8Array(r))}async onVerify(e,t,r,s){return xg.verify(e,Df(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return xg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await xg.importKey(e,t,{...r,name:this.name},s,i))}}class Bg extends wh{async onGenerateKey(e,t,r){const s=await xg.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onDeriveBits(e,t,r){return await xg.deriveBits({...e,public:Df(e.public)},Df(t),r)}async onExportKey(e,t){return xg.exportKey(e,Df(t))}async onImportKey(e,t,r,s,i){return Mf(await xg.importKey(e,t,{...r,name:this.name},s,i))}}class Rg extends Bf{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 Og extends Rg{constructor(){super(...arguments),this.type="private"}toJWK(){const e=kf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=sh.toUint8Array(this.data.toString()),r=Ru.parse(t,lf.PrivateKeyInfo),s=Ru.parse(r.privateKey,lf.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class Ug extends Rg{constructor(){super(...arguments),this.type="public"}toJWK(){const e=kf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class Tg{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=kf().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},a=r.filter(e=>this.privateKeyUsages.includes(e)),o=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new Og(n,t,a,i.privateKey),publicKey:new Ug(n,!0,o,i.publicKey)}}static async sign(e,t,r){const s=kf().sign(null,Buffer.from(r),t.data);return uc.toArrayBuffer(s)}static async verify(e,t,r,s){return kf().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 sh.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return yc.FromBase64Url(e.x)}default:return Promise.reject(new th("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 lf.EdPrivateKey;t.value=uc.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new lf.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?lf.idEd25519:lf.idX25519,n.privateKey=Ru.serialize(t);const a=Ru.serialize(n),o=sh.fromBufferSource(a,"PRIVATE KEY");return new Og(r,s,i,o)}if(e.x){const t=kf().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new Ug(r,s,i,t)}throw new th("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=sh.fromBufferSource(t,"PRIVATE KEY");return new Og(r,s,i,e)}case"spki":{const e=sh.fromBufferSource(t,"PUBLIC KEY");return new Ug(r,s,i,e)}case"raw":{const e=t,n=kf().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:yc.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new Ug(r,s,i,n)}default:return Promise.reject(new th("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}Tg.privateKeyUsages=["sign","deriveBits","deriveKey"],Tg.publicKeyUsages=["verify"];class Ng extends hf{async onGenerateKey(e,t,r){const s=await Tg.generateKey(e,t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onSign(e,t,r){const s=Df(t);return Tg.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=Df(t);return Tg.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=Df(t);return Tg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Mf(await Tg.importKey(e,t,r,s,i))}}class Dg extends uf{async onGenerateKey(e,t,r){const s=await Tg.generateKey(e,t,r);return{privateKey:Mf(s.privateKey),publicKey:Mf(s.publicKey)}}async onDeriveBits(e,t,r){const s=Df(t),i=Df(e.public),n=kf().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),a=kf().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),o=kf().diffieHellman({publicKey:n,privateKey:a});return new Uint8Array(o).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=Df(t);return Tg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Mf(await Tg.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Rg))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class Mg extends Bf{}class Pg extends gf{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=uc.toArrayBuffer(e.salt),a=e.hash.name.replace("-","");kf().pbkdf2(Df(t).data,Ef.Buffer.from(n),e.iterations,r>>3,a,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new Mg;return e.data=Ef.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,Mf(e)}throw new th("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Mg))throw new TypeError("key: Is not PBKDF CryptoKey")}}class Lg extends Bf{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Ou([Yu({name:"k",converter:_f})],Lg.prototype,"data",void 0);class Hg extends ff{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new Lg;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=kf().randomBytes(s>>3),Mf(i)}async onSign(e,t,r){const s=ag.getAlgorithmName(t.algorithm.hash),i=kf().createHmac(s,Df(t).data).update(Ef.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=ag.getAlgorithmName(t.algorithm.hash);return 0===kf().createHmac(i,Df(t).data).update(Ef.Buffer.from(s)).digest().compare(Ef.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Ju.fromJSON(t,{targetSchema:Lg});break;case"raw":n=new Lg,n.data=Ef.Buffer.from(t);break;default:throw new th("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,Mf(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return Wu.toJSON(Df(t));case"raw":return new Uint8Array(Df(t).data).buffer;default:throw new th("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Lg))throw new TypeError("key: Is not HMAC CryptoKey")}}class Vg extends Bf{}class Kg extends pf{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new th("Operation not supported");const n=new Vg;return n.data=Ef.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,Mf(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=kf().createHash(s).digest().length,n=r/8,a=uc.toUint8Array(e.info),o=kf().createHmac(s,uc.toUint8Array(e.salt)).update(uc.toUint8Array(Df(t).data)).digest(),c=[Ef.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(kf().createHmac(s,o).update(Ef.Buffer.concat([c[e-1],a,Ef.Buffer.from([e])])).digest());return Ef.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Df(e)instanceof Vg))throw new TypeError("key: Is not HKDF CryptoKey")}}class Qg{static digest(e,t){const r=kf().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(Ef.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class Fg extends mf{async onDigest(e,t){return Qg.digest(e,t)}}class $g extends yf{async onDigest(e,t){return Qg.digest(e,t)}}class Gg extends Sf{constructor(){var e;super(),this.providers.set(new Pf),this.providers.set(new jf),this.providers.set(new qf),this.providers.set(new Gf),this.providers.set(new zf),this.providers.set(new Wf),kf().getCiphers().includes("des-cbc")&&this.providers.set(new Xf),this.providers.set(new Zf),this.providers.set(new ig),this.providers.set(new ng),this.providers.set(new og),this.providers.set(new cg),this.providers.set(new vg),this.providers.set(new wg),this.providers.set(new fg),this.providers.set(new gg),this.providers.set(new pg),this.providers.set(new bg),this.providers.set(new Pg),this.providers.set(new Hg),this.providers.set(new Kg);const t=null===(e=/^v(\d+)/.exec(xf.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new Fg),this.providers.set(new $g));const r=kf().getHashes();r.includes("sha3-256")&&this.providers.set(new mg),r.includes("sha3-384")&&this.providers.set(new yg),r.includes("sha3-512")&&this.providers.set(new Ag),t&&parseInt(t,10)>=14&&(this.providers.set(new _g),this.providers.set(new Bg),this.providers.set(new Ng),this.providers.set(new Dg))}}var jg,qg,zg;a(909);class Wg{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(yc.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 Jg=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Ou([Cu({type:Ll.TeletexString})],Jg.prototype,"teletexString",void 0),Ou([Cu({type:Ll.PrintableString})],Jg.prototype,"printableString",void 0),Ou([Cu({type:Ll.UniversalString})],Jg.prototype,"universalString",void 0),Ou([Cu({type:Ll.Utf8String})],Jg.prototype,"utf8String",void 0),Ou([Cu({type:Ll.BmpString})],Jg.prototype,"bmpString",void 0),Jg=Ou([Eu({type:Pl.Choice})],Jg);let Yg=class extends Jg{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?yc.ToHex(this.anyValue):super.toString())}};Ou([Cu({type:Ll.IA5String})],Yg.prototype,"ia5String",void 0),Ou([Cu({type:Ll.Any})],Yg.prototype,"anyValue",void 0),Yg=Ou([Eu({type:Pl.Choice})],Yg);class Xg{constructor(e={}){this.type="",this.value=new Yg,Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Xg.prototype,"type",void 0),Ou([Cu({type:Yg})],Xg.prototype,"value",void 0);let Zg=jg=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,jg.prototype)}};Zg=jg=Ou([Eu({type:Pl.Set,itemType:Xg})],Zg);let ep=qg=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,qg.prototype)}};ep=qg=Ou([Eu({type:Pl.Sequence,itemType:Zg})],ep);let tp=zg=class extends ep{constructor(e){super(e),Object.setPrototypeOf(this,zg.prototype)}};tp=zg=Ou([Eu({type:Pl.Sequence})],tp);const rp={fromASN:e=>Wg.toString(tu.fromASN(e)),toASN:e=>tu.toASN(Wg.fromString(e))};class sp{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],sp.prototype,"typeId",void 0),Ou([Cu({type:Ll.Any,context:0})],sp.prototype,"value",void 0);class ip{constructor(e={}){this.partyName=new Jg,Object.assign(this,e)}}Ou([Cu({type:Jg,optional:!0,context:0,implicit:!0})],ip.prototype,"nameAssigner",void 0),Ou([Cu({type:Jg,context:1,implicit:!0})],ip.prototype,"partyName",void 0);let np=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:sp,context:0,implicit:!0})],np.prototype,"otherName",void 0),Ou([Cu({type:Ll.IA5String,context:1,implicit:!0})],np.prototype,"rfc822Name",void 0),Ou([Cu({type:Ll.IA5String,context:2,implicit:!0})],np.prototype,"dNSName",void 0),Ou([Cu({type:Ll.Any,context:3,implicit:!0})],np.prototype,"x400Address",void 0),Ou([Cu({type:tp,context:4,implicit:!1})],np.prototype,"directoryName",void 0),Ou([Cu({type:ip,context:5})],np.prototype,"ediPartyName",void 0),Ou([Cu({type:Ll.IA5String,context:6,implicit:!0})],np.prototype,"uniformResourceIdentifier",void 0),Ou([Cu({type:Ll.OctetString,context:7,implicit:!0,converter:rp})],np.prototype,"iPAddress",void 0),Ou([Cu({type:Ll.ObjectIdentifier,context:8,implicit:!0})],np.prototype,"registeredID",void 0),np=Ou([Eu({type:Pl.Choice})],np);const ap="1.3.6.1.5.5.7",op=`${ap}.3`,cp=`${ap}.48`,lp=`${cp}.1`,dp=`${cp}.2`,up=`${cp}.3`,hp=`${cp}.5`,fp="2.5.29";var gp;const pp=`${ap}.1.1`;class bp{constructor(e={}){this.accessMethod="",this.accessLocation=new np,Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],bp.prototype,"accessMethod",void 0),Ou([Cu({type:np})],bp.prototype,"accessLocation",void 0);let mp=gp=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,gp.prototype)}};mp=gp=Ou([Eu({type:Pl.Sequence,itemType:bp})],mp);const yp=`${fp}.35`;class Ap extends qd{}class Ip{constructor(e={}){e&&Object.assign(this,e)}}Ou([Cu({type:Ap,context:0,optional:!0,implicit:!0})],Ip.prototype,"keyIdentifier",void 0),Ou([Cu({type:np,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Ip.prototype,"authorityCertIssuer",void 0),Ou([Cu({type:Ll.Integer,context:2,optional:!0,implicit:!0,converter:Yd})],Ip.prototype,"authorityCertSerialNumber",void 0);const vp=`${fp}.19`;class wp{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Sp;Ou([Cu({type:Ll.Boolean,defaultValue:!1})],wp.prototype,"cA",void 0),Ou([Cu({type:Ll.Integer,optional:!0})],wp.prototype,"pathLenConstraint",void 0);let Ep=Sp=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Sp.prototype)}};var Cp;Ep=Sp=Ou([Eu({type:Pl.Sequence,itemType:np})],Ep);let kp=Cp=class extends Ep{constructor(e){super(e),Object.setPrototypeOf(this,Cp.prototype)}};var xp;kp=Cp=Ou([Eu({type:Pl.Sequence})],kp);const _p=`${fp}.32`;let Bp=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Ou([Cu({type:Ll.IA5String})],Bp.prototype,"ia5String",void 0),Ou([Cu({type:Ll.VisibleString})],Bp.prototype,"visibleString",void 0),Ou([Cu({type:Ll.BmpString})],Bp.prototype,"bmpString",void 0),Ou([Cu({type:Ll.Utf8String})],Bp.prototype,"utf8String",void 0),Bp=Ou([Eu({type:Pl.Choice})],Bp);class Rp{constructor(e={}){this.organization=new Bp,this.noticeNumbers=[],Object.assign(this,e)}}Ou([Cu({type:Bp})],Rp.prototype,"organization",void 0),Ou([Cu({type:Ll.Integer,repeated:"sequence"})],Rp.prototype,"noticeNumbers",void 0);class Op{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:Rp,optional:!0})],Op.prototype,"noticeRef",void 0),Ou([Cu({type:Bp,optional:!0})],Op.prototype,"explicitText",void 0);let Up=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:Ll.IA5String})],Up.prototype,"cPSuri",void 0),Ou([Cu({type:Op})],Up.prototype,"userNotice",void 0),Up=Ou([Eu({type:Pl.Choice})],Up);class Tp{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Tp.prototype,"policyQualifierId",void 0),Ou([Cu({type:Ll.Any})],Tp.prototype,"qualifier",void 0);class Np{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Np.prototype,"policyIdentifier",void 0),Ou([Cu({type:Tp,repeated:"sequence",optional:!0})],Np.prototype,"policyQualifiers",void 0);let Dp=xp=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,xp.prototype)}};Dp=xp=Ou([Eu({type:Pl.Sequence,itemType:Np})],Dp);let Mp=class{constructor(e=0){this.value=e}};Ou([Cu({type:Ll.Integer})],Mp.prototype,"value",void 0),Mp=Ou([Eu({type:Pl.Choice})],Mp);let Pp=class extends Mp{};var Lp;Pp=Ou([Eu({type:Pl.Choice})],Pp);const Hp=`${fp}.31`;var Vp;!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"}(Vp||(Vp={}));class Kp extends jd{toJSON(){const e=[],t=this.toNumber();return t&Vp.aACompromise&&e.push("aACompromise"),t&Vp.affiliationChanged&&e.push("affiliationChanged"),t&Vp.cACompromise&&e.push("cACompromise"),t&Vp.certificateHold&&e.push("certificateHold"),t&Vp.cessationOfOperation&&e.push("cessationOfOperation"),t&Vp.keyCompromise&&e.push("keyCompromise"),t&Vp.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&Vp.superseded&&e.push("superseded"),t&Vp.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let Qp=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:np,context:0,repeated:"sequence",implicit:!0})],Qp.prototype,"fullName",void 0),Ou([Cu({type:Zg,context:1,implicit:!0})],Qp.prototype,"nameRelativeToCRLIssuer",void 0),Qp=Ou([Eu({type:Pl.Choice})],Qp);class Fp{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:Qp,context:0,optional:!0})],Fp.prototype,"distributionPoint",void 0),Ou([Cu({type:Kp,context:1,optional:!0,implicit:!0})],Fp.prototype,"reasons",void 0),Ou([Cu({type:np,context:2,optional:!0,repeated:"sequence",implicit:!0})],Fp.prototype,"cRLIssuer",void 0);let $p=Lp=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Lp.prototype)}};var Gp;$p=Lp=Ou([Eu({type:Pl.Sequence,itemType:Fp})],$p);let jp=Gp=class extends $p{constructor(e){super(e),Object.setPrototypeOf(this,Gp.prototype)}};jp=Gp=Ou([Eu({type:Pl.Sequence,itemType:Fp})],jp);class qp{constructor(e={}){this.onlyContainsUserCerts=qp.ONLY,this.onlyContainsCACerts=qp.ONLY,this.indirectCRL=qp.ONLY,this.onlyContainsAttributeCerts=qp.ONLY,Object.assign(this,e)}}var zp;qp.ONLY=!1,Ou([Cu({type:Qp,context:0,optional:!0})],qp.prototype,"distributionPoint",void 0),Ou([Cu({type:Ll.Boolean,context:1,defaultValue:qp.ONLY,implicit:!0})],qp.prototype,"onlyContainsUserCerts",void 0),Ou([Cu({type:Ll.Boolean,context:2,defaultValue:qp.ONLY,implicit:!0})],qp.prototype,"onlyContainsCACerts",void 0),Ou([Cu({type:Kp,context:3,optional:!0,implicit:!0})],qp.prototype,"onlySomeReasons",void 0),Ou([Cu({type:Ll.Boolean,context:4,defaultValue:qp.ONLY,implicit:!0})],qp.prototype,"indirectCRL",void 0),Ou([Cu({type:Ll.Boolean,context:5,defaultValue:qp.ONLY,implicit:!0})],qp.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"}(zp||(zp={}));let Wp=class{constructor(e=zp.unspecified){this.reason=zp.unspecified,this.reason=e}toJSON(){return zp[this.reason]}toString(){return this.toJSON()}};var Jp;Ou([Cu({type:Ll.Enumerated})],Wp.prototype,"reason",void 0),Wp=Ou([Eu({type:Pl.Choice})],Wp);const Yp=`${fp}.37`;let Xp=Jp=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Jp.prototype)}};Xp=Jp=Ou([Eu({type:Pl.Sequence,itemType:Ll.ObjectIdentifier})],Xp);const Zp=`${op}.1`,eb=`${op}.2`,tb=`${op}.3`,rb=`${op}.4`,sb=`${op}.8`,ib=`${op}.9`;let nb=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Ou([Cu({type:Ll.Integer,converter:Yd})],nb.prototype,"value",void 0),nb=Ou([Eu({type:Pl.Choice})],nb);let ab=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var ob;Ou([Cu({type:Ll.GeneralizedTime})],ab.prototype,"value",void 0),ab=Ou([Eu({type:Pl.Choice})],ab);let cb=ob=class extends Ep{constructor(e){super(e),Object.setPrototypeOf(this,ob.prototype)}};cb=ob=Ou([Eu({type:Pl.Sequence})],cb);const lb=`${fp}.15`;var db,ub;!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"}(db||(db={}));class hb extends jd{toJSON(){const e=this.toNumber(),t=[];return e&db.cRLSign&&t.push("crlSign"),e&db.dataEncipherment&&t.push("dataEncipherment"),e&db.decipherOnly&&t.push("decipherOnly"),e&db.digitalSignature&&t.push("digitalSignature"),e&db.encipherOnly&&t.push("encipherOnly"),e&db.keyAgreement&&t.push("keyAgreement"),e&db.keyCertSign&&t.push("keyCertSign"),e&db.keyEncipherment&&t.push("keyEncipherment"),e&db.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class fb{constructor(e={}){this.base=new np,this.minimum=0,Object.assign(this,e)}}Ou([Cu({type:np})],fb.prototype,"base",void 0),Ou([Cu({type:Ll.Integer,context:0,defaultValue:0,implicit:!0})],fb.prototype,"minimum",void 0),Ou([Cu({type:Ll.Integer,context:1,optional:!0,implicit:!0})],fb.prototype,"maximum",void 0);let gb=ub=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,ub.prototype)}};gb=ub=Ou([Eu({type:Pl.Sequence,itemType:fb})],gb);class pb{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:gb,context:0,optional:!0,implicit:!0})],pb.prototype,"permittedSubtrees",void 0),Ou([Cu({type:gb,context:1,optional:!0,implicit:!0})],pb.prototype,"excludedSubtrees",void 0);class bb{constructor(e={}){Object.assign(this,e)}}var mb;Ou([Cu({type:Ll.Integer,context:0,implicit:!0,optional:!0,converter:Yd})],bb.prototype,"requireExplicitPolicy",void 0),Ou([Cu({type:Ll.Integer,context:1,implicit:!0,optional:!0,converter:Yd})],bb.prototype,"inhibitPolicyMapping",void 0);class yb{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],yb.prototype,"issuerDomainPolicy",void 0),Ou([Cu({type:Ll.ObjectIdentifier})],yb.prototype,"subjectDomainPolicy",void 0);let Ab=mb=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,mb.prototype)}};var Ib;Ab=mb=Ou([Eu({type:Pl.Sequence,itemType:yb})],Ab);const vb=`${fp}.17`;let wb=Ib=class extends Ep{constructor(e){super(e),Object.setPrototypeOf(this,Ib.prototype)}};wb=Ib=Ou([Eu({type:Pl.Sequence})],wb);class Sb{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Eb;Ou([Cu({type:Ll.ObjectIdentifier})],Sb.prototype,"type",void 0),Ou([Cu({type:Ll.Any,repeated:"set"})],Sb.prototype,"values",void 0);let Cb=Eb=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Eb.prototype)}};Cb=Eb=Ou([Eu({type:Pl.Sequence,itemType:Sb})],Cb);const kb=`${fp}.14`;class xb extends Ap{}class _b{constructor(e={}){Object.assign(this,e)}}var Bb,Rb;Ou([Cu({type:Ll.GeneralizedTime,context:0,implicit:!0,optional:!0})],_b.prototype,"notBefore",void 0),Ou([Cu({type:Ll.GeneralizedTime,context:1,implicit:!0,optional:!0})],_b.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Bb||(Bb={}));class Ob extends jd{toJSON(){const e=[],t=this.toNumber();return t&Bb.pKIXCertificate&&e.push("pKIXCertificate"),t&Bb.newExtensions&&e.push("newExtensions"),t&Bb.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Ub{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Ob,Object.assign(this,e)}}Ou([Cu({type:Ll.GeneralString})],Ub.prototype,"entrustVers",void 0),Ou([Cu({type:Ob})],Ub.prototype,"entrustInfoFlags",void 0);let Tb=Rb=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Rb.prototype)}};Tb=Rb=Ou([Eu({type:Pl.Sequence,itemType:bp})],Tb);class Nb{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof Nb&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Ic(e.parameters,this.parameters)||e.parameters===this.parameters)}}Ou([Cu({type:Ll.ObjectIdentifier})],Nb.prototype,"algorithm",void 0),Ou([Cu({type:Ll.Any,optional:!0})],Nb.prototype,"parameters",void 0);class Db{constructor(e={}){this.algorithm=new Nb,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Nb})],Db.prototype,"algorithm",void 0),Ou([Cu({type:Ll.BitString})],Db.prototype,"subjectPublicKey",void 0);let Mb=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}};Ou([Cu({type:Ll.UTCTime})],Mb.prototype,"utcTime",void 0),Ou([Cu({type:Ll.GeneralizedTime})],Mb.prototype,"generalTime",void 0),Mb=Ou([Eu({type:Pl.Choice})],Mb);class Pb{constructor(e){this.notBefore=new Mb(new Date),this.notAfter=new Mb(new Date),e&&(this.notBefore=new Mb(e.notBefore),this.notAfter=new Mb(e.notAfter))}}var Lb;Ou([Cu({type:Mb})],Pb.prototype,"notBefore",void 0),Ou([Cu({type:Mb})],Pb.prototype,"notAfter",void 0);class Hb{constructor(e={}){this.extnID="",this.critical=Hb.CRITICAL,this.extnValue=new qd,Object.assign(this,e)}}Hb.CRITICAL=!1,Ou([Cu({type:Ll.ObjectIdentifier})],Hb.prototype,"extnID",void 0),Ou([Cu({type:Ll.Boolean,defaultValue:Hb.CRITICAL})],Hb.prototype,"critical",void 0),Ou([Cu({type:qd})],Hb.prototype,"extnValue",void 0);let Vb=Lb=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Lb.prototype)}};var Kb;Vb=Lb=Ou([Eu({type:Pl.Sequence,itemType:Hb})],Vb),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(Kb||(Kb={}));class Qb{constructor(e={}){this.version=Kb.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new Nb,this.issuer=new tp,this.validity=new Pb,this.subject=new tp,this.subjectPublicKeyInfo=new Db,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,context:0,defaultValue:Kb.v1})],Qb.prototype,"version",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],Qb.prototype,"serialNumber",void 0),Ou([Cu({type:Nb})],Qb.prototype,"signature",void 0),Ou([Cu({type:tp})],Qb.prototype,"issuer",void 0),Ou([Cu({type:Pb})],Qb.prototype,"validity",void 0),Ou([Cu({type:tp})],Qb.prototype,"subject",void 0),Ou([Cu({type:Db})],Qb.prototype,"subjectPublicKeyInfo",void 0),Ou([Cu({type:Ll.BitString,context:1,implicit:!0,optional:!0})],Qb.prototype,"issuerUniqueID",void 0),Ou([Cu({type:Ll.BitString,context:2,implicit:!0,optional:!0})],Qb.prototype,"subjectUniqueID",void 0),Ou([Cu({type:Vb,context:3,optional:!0})],Qb.prototype,"extensions",void 0);class Fb{constructor(e={}){this.tbsCertificate=new Qb,this.signatureAlgorithm=new Nb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Qb})],Fb.prototype,"tbsCertificate",void 0),Ou([Cu({type:Nb})],Fb.prototype,"signatureAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],Fb.prototype,"signatureValue",void 0);class $b{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Mb,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,converter:Yd})],$b.prototype,"userCertificate",void 0),Ou([Cu({type:Mb})],$b.prototype,"revocationDate",void 0),Ou([Cu({type:Hb,optional:!0,repeated:"sequence"})],$b.prototype,"crlEntryExtensions",void 0);class Gb{constructor(e={}){this.signature=new Nb,this.issuer=new tp,this.thisUpdate=new Mb,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,optional:!0})],Gb.prototype,"version",void 0),Ou([Cu({type:Nb})],Gb.prototype,"signature",void 0),Ou([Cu({type:tp})],Gb.prototype,"issuer",void 0),Ou([Cu({type:Mb})],Gb.prototype,"thisUpdate",void 0),Ou([Cu({type:Mb,optional:!0})],Gb.prototype,"nextUpdate",void 0),Ou([Cu({type:$b,repeated:"sequence",optional:!0})],Gb.prototype,"revokedCertificates",void 0),Ou([Cu({type:Hb,optional:!0,context:0,repeated:"sequence"})],Gb.prototype,"crlExtensions",void 0);class jb{constructor(e={}){this.tbsCertList=new Gb,this.signatureAlgorithm=new Nb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Gb})],jb.prototype,"tbsCertList",void 0),Ou([Cu({type:Nb})],jb.prototype,"signatureAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],jb.prototype,"signature",void 0);class qb{constructor(e={}){this.issuer=new tp,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:tp})],qb.prototype,"issuer",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],qb.prototype,"serialNumber",void 0);let zb=class{constructor(e={}){Object.assign(this,e)}};var Wb;Ou([Cu({type:xb,context:0,implicit:!0})],zb.prototype,"subjectKeyIdentifier",void 0),Ou([Cu({type:qb})],zb.prototype,"issuerAndSerialNumber",void 0),zb=Ou([Eu({type:Pl.Choice})],zb),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"}(Wb||(Wb={}));let Jb=class extends Nb{};Jb=Ou([Eu({type:Pl.Sequence})],Jb);let Yb=class extends Nb{};Yb=Ou([Eu({type:Pl.Sequence})],Yb);let Xb=class extends Nb{};Xb=Ou([Eu({type:Pl.Sequence})],Xb);let Zb=class extends Nb{};Zb=Ou([Eu({type:Pl.Sequence})],Zb);let em=class extends Nb{};em=Ou([Eu({type:Pl.Sequence})],em);let tm=class extends Nb{};tm=Ou([Eu({type:Pl.Sequence})],tm);class rm{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var sm;Ou([Cu({type:Ll.ObjectIdentifier})],rm.prototype,"attrType",void 0),Ou([Cu({type:Ll.Any,repeated:"set"})],rm.prototype,"attrValues",void 0);class im{constructor(e={}){this.version=Wb.v0,this.sid=new zb,this.digestAlgorithm=new Jb,this.signatureAlgorithm=new Yb,this.signature=new qd,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],im.prototype,"version",void 0),Ou([Cu({type:zb})],im.prototype,"sid",void 0),Ou([Cu({type:Jb})],im.prototype,"digestAlgorithm",void 0),Ou([Cu({type:rm,repeated:"set",context:0,implicit:!0,optional:!0})],im.prototype,"signedAttrs",void 0),Ou([Cu({type:Yb})],im.prototype,"signatureAlgorithm",void 0),Ou([Cu({type:qd})],im.prototype,"signature",void 0),Ou([Cu({type:rm,repeated:"set",context:1,implicit:!0,optional:!0})],im.prototype,"unsignedAttrs",void 0);let nm=sm=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,sm.prototype)}};nm=sm=Ou([Eu({type:Pl.Set,itemType:im})],nm);let am=class extends Mb{};am=Ou([Eu({type:Pl.Choice})],am);let om=class extends im{};om=Ou([Eu({type:Pl.Sequence})],om);class cm{constructor(e={}){this.acIssuer=new np,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var lm;Ou([Cu({type:np})],cm.prototype,"acIssuer",void 0),Ou([Cu({type:Ll.Integer})],cm.prototype,"acSerial",void 0),Ou([Cu({type:Sb,repeated:"sequence"})],cm.prototype,"attrs",void 0);let dm=lm=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,lm.prototype)}};dm=lm=Ou([Eu({type:Pl.Sequence,itemType:Ll.ObjectIdentifier})],dm);class um{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,optional:!0})],um.prototype,"pathLenConstraint",void 0),Ou([Cu({type:dm,implicit:!0,context:0,optional:!0})],um.prototype,"permittedAttrs",void 0),Ou([Cu({type:dm,implicit:!0,context:1,optional:!0})],um.prototype,"excludedAttrs",void 0),Ou([Cu({type:Ll.Boolean,defaultValue:!0})],um.prototype,"permitUnSpecified",void 0);class hm{constructor(e={}){this.issuer=new Ep,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var fm;Ou([Cu({type:Ep})],hm.prototype,"issuer",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],hm.prototype,"serial",void 0),Ou([Cu({type:Ll.BitString,optional:!0})],hm.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(fm||(fm={}));class gm{constructor(e={}){this.digestedObjectType=fm.publicKey,this.digestAlgorithm=new Nb,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.Enumerated})],gm.prototype,"digestedObjectType",void 0),Ou([Cu({type:Ll.ObjectIdentifier,optional:!0})],gm.prototype,"otherObjectTypeID",void 0),Ou([Cu({type:Nb})],gm.prototype,"digestAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],gm.prototype,"objectDigest",void 0);class pm{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:Ep,optional:!0})],pm.prototype,"issuerName",void 0),Ou([Cu({type:hm,context:0,implicit:!0,optional:!0})],pm.prototype,"baseCertificateID",void 0),Ou([Cu({type:gm,context:1,implicit:!0,optional:!0})],pm.prototype,"objectDigestInfo",void 0);let bm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:np,repeated:"sequence"})],bm.prototype,"v1Form",void 0),Ou([Cu({type:pm,context:0,implicit:!0})],bm.prototype,"v2Form",void 0),bm=Ou([Eu({type:Pl.Choice})],bm);class mm{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Ou([Cu({type:Ll.GeneralizedTime})],mm.prototype,"notBeforeTime",void 0),Ou([Cu({type:Ll.GeneralizedTime})],mm.prototype,"notAfterTime",void 0);class ym{constructor(e={}){Object.assign(this,e)}}var Am,Im,vm;Ou([Cu({type:hm,implicit:!0,context:0,optional:!0})],ym.prototype,"baseCertificateID",void 0),Ou([Cu({type:Ep,implicit:!0,context:1,optional:!0})],ym.prototype,"entityName",void 0),Ou([Cu({type:gm,implicit:!0,context:2,optional:!0})],ym.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(Am||(Am={}));class wm{constructor(e={}){this.version=Am.v2,this.holder=new ym,this.issuer=new bm,this.signature=new Nb,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new mm,this.attributes=[],Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],wm.prototype,"version",void 0),Ou([Cu({type:ym})],wm.prototype,"holder",void 0),Ou([Cu({type:bm})],wm.prototype,"issuer",void 0),Ou([Cu({type:Nb})],wm.prototype,"signature",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],wm.prototype,"serialNumber",void 0),Ou([Cu({type:mm})],wm.prototype,"attrCertValidityPeriod",void 0),Ou([Cu({type:Sb,repeated:"sequence"})],wm.prototype,"attributes",void 0),Ou([Cu({type:Ll.BitString,optional:!0})],wm.prototype,"issuerUniqueID",void 0),Ou([Cu({type:Vb,optional:!0})],wm.prototype,"extensions",void 0);class Sm{constructor(e={}){this.acinfo=new wm,this.signatureAlgorithm=new Nb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:wm})],Sm.prototype,"acinfo",void 0),Ou([Cu({type:Nb})],Sm.prototype,"signatureAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],Sm.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"}(Im||(Im={}));class Em extends jd{}class Cm{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier,implicit:!0,context:0})],Cm.prototype,"type",void 0),Ou([Cu({type:Ll.Any,implicit:!0,context:1})],Cm.prototype,"value",void 0);class km{constructor(e={}){this.policyId="",this.classList=new Em(Im.unclassified),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],km.prototype,"policyId",void 0),Ou([Cu({type:Em,defaultValue:new Em(Im.unclassified)})],km.prototype,"classList",void 0),Ou([Cu({type:Cm,repeated:"set"})],km.prototype,"securityCategories",void 0);class xm{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:qd})],xm.prototype,"cotets",void 0),Ou([Cu({type:Ll.ObjectIdentifier})],xm.prototype,"oid",void 0),Ou([Cu({type:Ll.Utf8String})],xm.prototype,"string",void 0);class _m{constructor(e={}){this.values=[],Object.assign(this,e)}}Ou([Cu({type:Ep,implicit:!0,context:0,optional:!0})],_m.prototype,"policyAuthority",void 0),Ou([Cu({type:xm,repeated:"sequence"})],_m.prototype,"values",void 0);class Bm{constructor(e={}){this.targetCertificate=new hm,Object.assign(this,e)}}Ou([Cu({type:hm})],Bm.prototype,"targetCertificate",void 0),Ou([Cu({type:np,optional:!0})],Bm.prototype,"targetName",void 0),Ou([Cu({type:gm,optional:!0})],Bm.prototype,"certDigestInfo",void 0);let Rm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:np,context:0,implicit:!0})],Rm.prototype,"targetName",void 0),Ou([Cu({type:np,context:1,implicit:!0})],Rm.prototype,"targetGroup",void 0),Ou([Cu({type:Bm,context:2,implicit:!0})],Rm.prototype,"targetCert",void 0),Rm=Ou([Eu({type:Pl.Choice})],Rm);let Om=vm=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,vm.prototype)}};var Um;Om=vm=Ou([Eu({type:Pl.Sequence,itemType:Rm})],Om);let Tm=Um=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Um.prototype)}};Tm=Um=Ou([Eu({type:Pl.Sequence,itemType:Om})],Tm);class Nm{constructor(e={}){Object.assign(this,e)}}Ou([Cu({type:Ep,implicit:!0,context:0,optional:!0})],Nm.prototype,"roleAuthority",void 0),Ou([Cu({type:np,implicit:!0,context:1})],Nm.prototype,"roleName",void 0);class Dm{constructor(e={}){this.service=new np,this.ident=new np,Object.assign(this,e)}}var Mm;Ou([Cu({type:np})],Dm.prototype,"service",void 0),Ou([Cu({type:np})],Dm.prototype,"ident",void 0),Ou([Cu({type:qd,optional:!0})],Dm.prototype,"authInfo",void 0);class Pm{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Pm.prototype,"otherCertFormat",void 0),Ou([Cu({type:Ll.Any})],Pm.prototype,"otherCert",void 0);let Lm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:Fb})],Lm.prototype,"certificate",void 0),Ou([Cu({type:Sm,context:2,implicit:!0})],Lm.prototype,"v2AttrCert",void 0),Ou([Cu({type:Pm,context:3,implicit:!0})],Lm.prototype,"other",void 0),Lm=Ou([Eu({type:Pl.Choice})],Lm);let Hm=Mm=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,Mm.prototype)}};Hm=Mm=Ou([Eu({type:Pl.Set,itemType:Lm})],Hm);class Vm{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Vm.prototype,"contentType",void 0),Ou([Cu({type:Ll.Any,context:0})],Vm.prototype,"content",void 0);let Km=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:qd})],Km.prototype,"single",void 0),Ou([Cu({type:Ll.Any})],Km.prototype,"any",void 0),Km=Ou([Eu({type:Pl.Choice})],Km);class Qm{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],Qm.prototype,"eContentType",void 0),Ou([Cu({type:Km,context:0,optional:!0})],Qm.prototype,"eContent",void 0);let Fm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:qd,context:0,implicit:!0,optional:!0})],Fm.prototype,"value",void 0),Ou([Cu({type:qd,converter:ru,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Fm.prototype,"constructedValue",void 0),Fm=Ou([Eu({type:Pl.Choice})],Fm);class $m{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new Zb,Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],$m.prototype,"contentType",void 0),Ou([Cu({type:Zb})],$m.prototype,"contentEncryptionAlgorithm",void 0),Ou([Cu({type:Fm,optional:!0})],$m.prototype,"encryptedContent",void 0);class Gm{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var jm;Ou([Cu({type:Ll.ObjectIdentifier})],Gm.prototype,"keyAttrId",void 0),Ou([Cu({type:Ll.Any,optional:!0})],Gm.prototype,"keyAttr",void 0);class qm{constructor(e={}){this.subjectKeyIdentifier=new xb,Object.assign(this,e)}}Ou([Cu({type:xb})],qm.prototype,"subjectKeyIdentifier",void 0),Ou([Cu({type:Ll.GeneralizedTime,optional:!0})],qm.prototype,"date",void 0),Ou([Cu({type:Gm,optional:!0})],qm.prototype,"other",void 0);let zm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:qm,context:0,implicit:!0,optional:!0})],zm.prototype,"rKeyId",void 0),Ou([Cu({type:qb,optional:!0})],zm.prototype,"issuerAndSerialNumber",void 0),zm=Ou([Eu({type:Pl.Choice})],zm);class Wm{constructor(e={}){this.rid=new zm,this.encryptedKey=new qd,Object.assign(this,e)}}Ou([Cu({type:zm})],Wm.prototype,"rid",void 0),Ou([Cu({type:qd})],Wm.prototype,"encryptedKey",void 0);let Jm=jm=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,jm.prototype)}};Jm=jm=Ou([Eu({type:Pl.Sequence,itemType:Wm})],Jm);class Ym{constructor(e={}){this.algorithm=new Nb,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Nb})],Ym.prototype,"algorithm",void 0),Ou([Cu({type:Ll.BitString})],Ym.prototype,"publicKey",void 0);let Xm=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:xb,context:0,implicit:!0,optional:!0})],Xm.prototype,"subjectKeyIdentifier",void 0),Ou([Cu({type:Ym,context:1,implicit:!0,optional:!0})],Xm.prototype,"originatorKey",void 0),Ou([Cu({type:qb,optional:!0})],Xm.prototype,"issuerAndSerialNumber",void 0),Xm=Ou([Eu({type:Pl.Choice})],Xm);class Zm{constructor(e={}){this.version=Wb.v3,this.originator=new Xm,this.keyEncryptionAlgorithm=new Xb,this.recipientEncryptedKeys=new Jm,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],Zm.prototype,"version",void 0),Ou([Cu({type:Xm,context:0})],Zm.prototype,"originator",void 0),Ou([Cu({type:qd,context:1,optional:!0})],Zm.prototype,"ukm",void 0),Ou([Cu({type:Xb})],Zm.prototype,"keyEncryptionAlgorithm",void 0),Ou([Cu({type:Jm})],Zm.prototype,"recipientEncryptedKeys",void 0);let ey=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:xb,context:0,implicit:!0})],ey.prototype,"subjectKeyIdentifier",void 0),Ou([Cu({type:qb})],ey.prototype,"issuerAndSerialNumber",void 0),ey=Ou([Eu({type:Pl.Choice})],ey);class ty{constructor(e={}){this.version=Wb.v0,this.rid=new ey,this.keyEncryptionAlgorithm=new Xb,this.encryptedKey=new qd,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],ty.prototype,"version",void 0),Ou([Cu({type:ey})],ty.prototype,"rid",void 0),Ou([Cu({type:Xb})],ty.prototype,"keyEncryptionAlgorithm",void 0),Ou([Cu({type:qd})],ty.prototype,"encryptedKey",void 0);class ry{constructor(e={}){this.keyIdentifier=new qd,Object.assign(this,e)}}Ou([Cu({type:qd})],ry.prototype,"keyIdentifier",void 0),Ou([Cu({type:Ll.GeneralizedTime,optional:!0})],ry.prototype,"date",void 0),Ou([Cu({type:Gm,optional:!0})],ry.prototype,"other",void 0);class sy{constructor(e={}){this.version=Wb.v4,this.kekid=new ry,this.keyEncryptionAlgorithm=new Xb,this.encryptedKey=new qd,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],sy.prototype,"version",void 0),Ou([Cu({type:ry})],sy.prototype,"kekid",void 0),Ou([Cu({type:Xb})],sy.prototype,"keyEncryptionAlgorithm",void 0),Ou([Cu({type:qd})],sy.prototype,"encryptedKey",void 0);class iy{constructor(e={}){this.version=Wb.v0,this.keyEncryptionAlgorithm=new Xb,this.encryptedKey=new qd,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],iy.prototype,"version",void 0),Ou([Cu({type:tm,context:0,optional:!0})],iy.prototype,"keyDerivationAlgorithm",void 0),Ou([Cu({type:Xb})],iy.prototype,"keyEncryptionAlgorithm",void 0),Ou([Cu({type:qd})],iy.prototype,"encryptedKey",void 0);class ny{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],ny.prototype,"oriType",void 0),Ou([Cu({type:Ll.Any})],ny.prototype,"oriValue",void 0);let ay=class{constructor(e={}){Object.assign(this,e)}};var oy;Ou([Cu({type:ty,optional:!0})],ay.prototype,"ktri",void 0),Ou([Cu({type:Zm,context:1,implicit:!0,optional:!0})],ay.prototype,"kari",void 0),Ou([Cu({type:sy,context:2,implicit:!0,optional:!0})],ay.prototype,"kekri",void 0),Ou([Cu({type:iy,context:3,implicit:!0,optional:!0})],ay.prototype,"pwri",void 0),Ou([Cu({type:ny,context:4,implicit:!0,optional:!0})],ay.prototype,"ori",void 0),ay=Ou([Eu({type:Pl.Choice})],ay);let cy=oy=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,oy.prototype)}};var ly;cy=oy=Ou([Eu({type:Pl.Set,itemType:ay})],cy);class dy{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],dy.prototype,"otherRevInfoFormat",void 0),Ou([Cu({type:Ll.Any})],dy.prototype,"otherRevInfo",void 0);let uy=class{constructor(e={}){this.other=new dy,Object.assign(this,e)}};Ou([Cu({type:dy,context:1,implicit:!0})],uy.prototype,"other",void 0),uy=Ou([Eu({type:Pl.Choice})],uy);let hy=ly=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,ly.prototype)}};hy=ly=Ou([Eu({type:Pl.Set,itemType:uy})],hy);class fy{constructor(e={}){Object.assign(this,e)}}var gy;Ou([Cu({type:Hm,context:0,implicit:!0,optional:!0})],fy.prototype,"certs",void 0),Ou([Cu({type:hy,context:1,implicit:!0,optional:!0})],fy.prototype,"crls",void 0);let py=gy=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,gy.prototype)}};py=gy=Ou([Eu({type:Pl.Set,itemType:rm})],py);class by{constructor(e={}){this.version=Wb.v0,this.recipientInfos=new cy,this.encryptedContentInfo=new $m,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],by.prototype,"version",void 0),Ou([Cu({type:fy,context:0,implicit:!0,optional:!0})],by.prototype,"originatorInfo",void 0),Ou([Cu({type:cy})],by.prototype,"recipientInfos",void 0),Ou([Cu({type:$m})],by.prototype,"encryptedContentInfo",void 0),Ou([Cu({type:py,context:1,implicit:!0,optional:!0})],by.prototype,"unprotectedAttrs",void 0);const my="1.2.840.113549.1.7.2";var yy;let Ay=yy=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,yy.prototype)}};Ay=yy=Ou([Eu({type:Pl.Set,itemType:Jb})],Ay);class Iy{constructor(e={}){this.version=Wb.v0,this.digestAlgorithms=new Ay,this.encapContentInfo=new Qm,this.signerInfos=new nm,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],Iy.prototype,"version",void 0),Ou([Cu({type:Ay})],Iy.prototype,"digestAlgorithms",void 0),Ou([Cu({type:Qm})],Iy.prototype,"encapContentInfo",void 0),Ou([Cu({type:Hm,context:0,implicit:!0,optional:!0})],Iy.prototype,"certificates",void 0),Ou([Cu({type:hy,context:1,implicit:!0,optional:!0})],Iy.prototype,"crls",void 0),Ou([Cu({type:nm})],Iy.prototype,"signerInfos",void 0);const vy="1.2.840.10045.2.1",wy="1.2.840.10045.4.1",Sy="1.2.840.10045.4.3.1",Ey="1.2.840.10045.4.3.2",Cy="1.2.840.10045.4.3.3",ky="1.2.840.10045.4.3.4",xy="1.2.840.10045.3.1.7",_y="1.3.132.0.34",By="1.3.132.0.35";function Ry(e){return new Nb({algorithm:e})}const Oy=Ry(wy),Uy=(Ry(Sy),Ry(Ey)),Ty=Ry(Cy),Ny=Ry(ky);let Dy=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:Ll.ObjectIdentifier})],Dy.prototype,"fieldType",void 0),Ou([Cu({type:Ll.Any})],Dy.prototype,"parameters",void 0),Dy=Ou([Eu({type:Pl.Sequence})],Dy);let My=class{constructor(e={}){Object.assign(this,e)}};var Py;Ou([Cu({type:Ll.OctetString})],My.prototype,"a",void 0),Ou([Cu({type:Ll.OctetString})],My.prototype,"b",void 0),Ou([Cu({type:Ll.BitString,optional:!0})],My.prototype,"seed",void 0),My=Ou([Eu({type:Pl.Sequence})],My),function(e){e[e.ecpVer1=1]="ecpVer1"}(Py||(Py={}));let Ly=class{constructor(e={}){this.version=Py.ecpVer1,Object.assign(this,e)}};Ou([Cu({type:Ll.Integer})],Ly.prototype,"version",void 0),Ou([Cu({type:Dy})],Ly.prototype,"fieldID",void 0),Ou([Cu({type:My})],Ly.prototype,"curve",void 0),Ou([Cu({type:class extends qd{}})],Ly.prototype,"base",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],Ly.prototype,"order",void 0),Ou([Cu({type:Ll.Integer,optional:!0})],Ly.prototype,"cofactor",void 0),Ly=Ou([Eu({type:Pl.Sequence})],Ly);let Hy=class{constructor(e={}){Object.assign(this,e)}};Ou([Cu({type:Ll.ObjectIdentifier})],Hy.prototype,"namedCurve",void 0),Ou([Cu({type:Ll.Null})],Hy.prototype,"implicitCurve",void 0),Ou([Cu({type:Ly})],Hy.prototype,"specifiedCurve",void 0),Hy=Ou([Eu({type:Pl.Choice})],Hy);class Vy{constructor(e={}){this.version=1,this.privateKey=new qd,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],Vy.prototype,"version",void 0),Ou([Cu({type:qd})],Vy.prototype,"privateKey",void 0),Ou([Cu({type:Hy,context:0,optional:!0})],Vy.prototype,"parameters",void 0),Ou([Cu({type:Ll.BitString,context:1,optional:!0})],Vy.prototype,"publicKey",void 0);class Ky{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,converter:Yd})],Ky.prototype,"r",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],Ky.prototype,"s",void 0);const Qy="1.2.840.113549.1.1",Fy=`${Qy}.1`,$y=`${Qy}.7`,Gy=`${Qy}.9`,jy=`${Qy}.10`,qy=`${Qy}.2`,zy=`${Qy}.4`,Wy=`${Qy}.5`,Jy=`${Qy}.14`,Yy=`${Qy}.11`,Xy=`${Qy}.12`,Zy=`${Qy}.13`,eA=`${Qy}.15`,tA=`${Qy}.16`,rA="1.3.14.3.2.26",sA="2.16.840.1.101.3.4.2.4",iA="2.16.840.1.101.3.4.2.1",nA="2.16.840.1.101.3.4.2.2",aA="2.16.840.1.101.3.4.2.3",oA=`${Qy}.8`;function cA(e){return new Nb({algorithm:e,parameters:null})}cA("1.2.840.113549.2.2"),cA("1.2.840.113549.2.5");const lA=cA(rA),dA=(cA(sA),cA(iA),cA(nA),cA(aA),cA("2.16.840.1.101.3.4.2.5"),cA("2.16.840.1.101.3.4.2.6"),new Nb({algorithm:oA,parameters:Ru.serialize(lA)})),uA=new Nb({algorithm:Gy,parameters:Ru.serialize(tu.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});cA(Fy),cA(qy),cA(zy),cA(Wy),cA(eA),cA(tA),cA(Xy),cA(Zy),cA(eA),cA(tA);class hA{constructor(e={}){this.hashAlgorithm=new Nb(lA),this.maskGenAlgorithm=new Nb({algorithm:oA,parameters:Ru.serialize(lA)}),this.pSourceAlgorithm=new Nb(uA),Object.assign(this,e)}}Ou([Cu({type:Nb,context:0,defaultValue:lA})],hA.prototype,"hashAlgorithm",void 0),Ou([Cu({type:Nb,context:1,defaultValue:dA})],hA.prototype,"maskGenAlgorithm",void 0),Ou([Cu({type:Nb,context:2,defaultValue:uA})],hA.prototype,"pSourceAlgorithm",void 0),new Nb({algorithm:$y,parameters:Ru.serialize(new hA)});class fA{constructor(e={}){this.hashAlgorithm=new Nb(lA),this.maskGenAlgorithm=new Nb({algorithm:oA,parameters:Ru.serialize(lA)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Ou([Cu({type:Nb,context:0,defaultValue:lA})],fA.prototype,"hashAlgorithm",void 0),Ou([Cu({type:Nb,context:1,defaultValue:dA})],fA.prototype,"maskGenAlgorithm",void 0),Ou([Cu({type:Ll.Integer,context:2,defaultValue:20})],fA.prototype,"saltLength",void 0),Ou([Cu({type:Ll.Integer,context:3,defaultValue:1})],fA.prototype,"trailerField",void 0),new Nb({algorithm:jy,parameters:Ru.serialize(new fA)});class gA{constructor(e={}){this.digestAlgorithm=new Nb,this.digest=new qd,Object.assign(this,e)}}var pA;Ou([Cu({type:Nb})],gA.prototype,"digestAlgorithm",void 0),Ou([Cu({type:qd})],gA.prototype,"digest",void 0);class bA{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.Integer,converter:Yd})],bA.prototype,"prime",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],bA.prototype,"exponent",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],bA.prototype,"coefficient",void 0);let mA=pA=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,pA.prototype)}};mA=pA=Ou([Eu({type:Pl.Sequence,itemType:bA})],mA);class yA{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)}}Ou([Cu({type:Ll.Integer})],yA.prototype,"version",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"modulus",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"publicExponent",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"privateExponent",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"prime1",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"prime2",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"exponent1",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"exponent2",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],yA.prototype,"coefficient",void 0),Ou([Cu({type:mA,optional:!0})],yA.prototype,"otherPrimeInfos",void 0);class AA{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var IA;Ou([Cu({type:Ll.Integer,converter:Yd})],AA.prototype,"modulus",void 0),Ou([Cu({type:Ll.Integer,converter:Yd})],AA.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"}(IA||(IA={}));const vA=IA;var wA=function(e,t){return wA=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])},wA(e,t)};function SA(e,t){function r(){this.constructor=e}wA(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function EA(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 CA(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)a.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 a}function kA(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(CA(arguments[t]));return e}function xA(e){return!!e.useClass}function _A(e){return!!e.useFactory}var BA=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,kA(t))}}),t},e}();function RA(e){return"string"==typeof e||"symbol"==typeof e}function OA(e){return"object"==typeof e&&"token"in e&&"transform"in e}function UA(e){return!!e.useToken}function TA(e){return null!=e.useValue}var NA=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 DA=NA,MA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return SA(t,e),t}(DA),PA=function(){this.scopedResolutions=new Map};var LA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return SA(t,e),t}(DA),HA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return SA(t,e),t}(DA);const VA=function(){this.preResolution=new LA,this.postResolution=new HA};var KA=new Map,QA=function(){function e(e){this.parent=e,this._registry=new MA,this.interceptors=new VA,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:vA.Transient}),this.ensureNotDisposed(),s=function(e){return xA(e)||TA(e)||UA(e)||_A(e)}(t)?t:{useClass:t},UA(s))for(var i=[e],n=s;null!=n;){var a=n.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+kA(i,[a]).join(" -> "));i.push(a);var o=this._registry.get(a);n=o&&UA(o.provider)?o.provider:null}if((r.lifecycle===vA.Singleton||r.lifecycle==vA.ContainerScoped||r.lifecycle==vA.ResolutionScoped)&&(TA(s)||_A(s)))throw new Error('Cannot use lifecycle "'+vA[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(),RA(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(),RA(e)){if(RA(t))return this.register(e,{useToken:t},{lifecycle:vA.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:vA.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!RA(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:vA.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new PA),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&RA(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 BA}(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=EA(this.interceptors.preResolution.getAll(e)),a=n.next();!a.done;a=n.next()){var o=a.value;"Once"!=o.options.frequency&&i.push(o),o.callback(e,t)}}catch(e){r={error:e}}finally{try{a&&!a.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 a=EA(this.interceptors.postResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var c=o.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===vA.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===vA.Singleton,i=e.options.lifecycle===vA.ContainerScoped,n=s||i;return r=TA(e.provider)?e.provider.useValue:UA(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):xA(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):_A(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===vA.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new PA),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&RA(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 a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},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=EA(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=CA(s.value,2),n=i[0],a=i[1];this._registry.setAll(n,a.filter(function(e){return!TA(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=EA(this._registry.entries()),n=i.next();!n.done;n=i.next()){var a=CA(n.value,2),o=a[0],c=a[1];c.some(function(e){return e.options.lifecycle===vA.ContainerScoped})&&s._registry.setAll(o,c.map(function(e){return e.options.lifecycle===vA.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 a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(n){return function(o){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)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 a.label++,{value:n[1],done:!1};case 5:a.label++,s=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){a.label=n[1];break}if(6===n[0]&&a.label<i[1]){a.label=i[1],i=n;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(n);break}i[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}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,o])}}}(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 BA)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=KA.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,kA([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,a,o,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?OA(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,kA([r.resolveAll(s.token,new PA,s.isOptional)],s.transformArgs)):(a=r.resolve(s.transform)).transform.apply(a,kA([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new PA,s.isOptional):r.resolve(s.token,e,s.isOptional):OA(s)?(o=r.resolve(s.transform,e)).transform.apply(o,kA([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=CA(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),kA([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}(),FA=new QA;const $A=function(e){return function(t){KA.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){FA.register(e,t)}):FA.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 GA;class jA{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Ou([Cu({type:Ll.ObjectIdentifier})],jA.prototype,"attrId",void 0),Ou([Cu({type:Ll.Any,repeated:"set"})],jA.prototype,"attrValues",void 0);let qA=GA=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,GA.prototype)}};var zA;qA=GA=Ou([Eu({type:Pl.Sequence,itemType:jA})],qA);let WA=zA=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,zA.prototype)}};WA=zA=Ou([Eu({type:Pl.Sequence,itemType:Vm})],WA);class JA{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],JA.prototype,"certId",void 0),Ou([Cu({type:Ll.Any,context:0})],JA.prototype,"certValue",void 0);class YA{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],YA.prototype,"crlId",void 0),Ou([Cu({type:Ll.Any,context:0})],YA.prototype,"crltValue",void 0);class XA extends qd{}class ZA{constructor(e={}){this.encryptionAlgorithm=new Nb,this.encryptedData=new XA,Object.assign(this,e)}}var eI,tI;Ou([Cu({type:Nb})],ZA.prototype,"encryptionAlgorithm",void 0),Ou([Cu({type:XA})],ZA.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(tI||(tI={}));class rI extends qd{}let sI=eI=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,eI.prototype)}};sI=eI=Ou([Eu({type:Pl.Sequence,itemType:Sb})],sI);class iI{constructor(e={}){this.version=tI.v1,this.privateKeyAlgorithm=new Nb,this.privateKey=new rI,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],iI.prototype,"version",void 0),Ou([Cu({type:Nb})],iI.prototype,"privateKeyAlgorithm",void 0),Ou([Cu({type:rI})],iI.prototype,"privateKey",void 0),Ou([Cu({type:sI,implicit:!0,context:0,optional:!0})],iI.prototype,"attributes",void 0);let nI=class extends iI{};nI=Ou([Eu({type:Pl.Sequence})],nI);let aI=class extends ZA{};aI=Ou([Eu({type:Pl.Sequence})],aI);class oI{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],oI.prototype,"secretTypeId",void 0),Ou([Cu({type:Ll.Any,context:0})],oI.prototype,"secretValue",void 0);class cI{constructor(e={}){this.mac=new gA,this.macSalt=new qd,this.iterations=1,Object.assign(this,e)}}Ou([Cu({type:gA})],cI.prototype,"mac",void 0),Ou([Cu({type:qd})],cI.prototype,"macSalt",void 0),Ou([Cu({type:Ll.Integer,defaultValue:1})],cI.prototype,"iterations",void 0);class lI{constructor(e={}){this.version=3,this.authSafe=new Vm,this.macData=new cI,Object.assign(this,e)}}var dI;Ou([Cu({type:Ll.Integer})],lI.prototype,"version",void 0),Ou([Cu({type:Vm})],lI.prototype,"authSafe",void 0),Ou([Cu({type:cI,optional:!0})],lI.prototype,"macData",void 0);class uI{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:Ll.ObjectIdentifier})],uI.prototype,"bagId",void 0),Ou([Cu({type:Ll.Any,context:0})],uI.prototype,"bagValue",void 0),Ou([Cu({type:jA,repeated:"set",optional:!0})],uI.prototype,"bagAttributes",void 0);let hI=dI=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,dI.prototype)}};var fI,gI,pI;hI=dI=Ou([Eu({type:Pl.Sequence,itemType:uI})],hI);const bI="1.2.840.113549.1.9",mI=`${bI}.7`,yI=`${bI}.14`;let AI=class extends Jg{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Ou([Cu({type:Ll.IA5String})],AI.prototype,"ia5String",void 0),AI=Ou([Eu({type:Pl.Choice})],AI);let II=class extends Vm{};II=Ou([Eu({type:Pl.Sequence})],II);let vI=class extends lI{};vI=Ou([Eu({type:Pl.Sequence})],vI);let wI=class extends ZA{};wI=Ou([Eu({type:Pl.Sequence})],wI);let SI=class{constructor(e=""){this.value=e}toString(){return this.value}};Ou([Cu({type:Ll.IA5String})],SI.prototype,"value",void 0),SI=Ou([Eu({type:Pl.Choice})],SI);let EI=class extends AI{};EI=Ou([Eu({type:Pl.Choice})],EI);let CI=class extends Jg{};CI=Ou([Eu({type:Pl.Choice})],CI);let kI=class{constructor(e=new Date){this.value=e}};Ou([Cu({type:Ll.GeneralizedTime})],kI.prototype,"value",void 0),kI=Ou([Eu({type:Pl.Choice})],kI);let xI=class extends Jg{};xI=Ou([Eu({type:Pl.Choice})],xI);let _I=class{constructor(e="M"){this.value=e}toString(){return this.value}};Ou([Cu({type:Ll.PrintableString})],_I.prototype,"value",void 0),_I=Ou([Eu({type:Pl.Choice})],_I);let BI=class{constructor(e=""){this.value=e}toString(){return this.value}};Ou([Cu({type:Ll.PrintableString})],BI.prototype,"value",void 0),BI=Ou([Eu({type:Pl.Choice})],BI);let RI=class extends BI{};RI=Ou([Eu({type:Pl.Choice})],RI);let OI=class extends Jg{};OI=Ou([Eu({type:Pl.Choice})],OI);let UI=class{constructor(e=""){this.value=e}toString(){return this.value}};Ou([Cu({type:Ll.ObjectIdentifier})],UI.prototype,"value",void 0),UI=Ou([Eu({type:Pl.Choice})],UI);let TI=class extends Mb{};TI=Ou([Eu({type:Pl.Choice})],TI);let NI=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Ou([Cu({type:Ll.Integer})],NI.prototype,"value",void 0),NI=Ou([Eu({type:Pl.Choice})],NI);let DI=class extends im{};DI=Ou([Eu({type:Pl.Sequence})],DI);let MI=class extends Jg{};MI=Ou([Eu({type:Pl.Choice})],MI);let PI=fI=class extends Vb{constructor(e){super(e),Object.setPrototypeOf(this,fI.prototype)}};PI=fI=Ou([Eu({type:Pl.Sequence})],PI);let LI=gI=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,gI.prototype)}};LI=gI=Ou([Eu({type:Pl.Set,itemType:rm})],LI);let HI=class{constructor(e=""){this.value=e}toString(){return this.value}};Ou([Cu({type:Ll.BmpString})],HI.prototype,"value",void 0),HI=Ou([Eu({type:Pl.Choice})],HI);let VI=class extends Nb{};VI=Ou([Eu({type:Pl.Sequence})],VI);let KI=pI=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,pI.prototype)}};var QI;KI=pI=Ou([Eu({type:Pl.Sequence,itemType:VI})],KI);let FI=QI=class extends Bu{constructor(e){super(e),Object.setPrototypeOf(this,QI.prototype)}};FI=QI=Ou([Eu({type:Pl.Sequence,itemType:Sb})],FI);class $I{constructor(e={}){this.version=0,this.subject=new tp,this.subjectPKInfo=new Db,this.attributes=new FI,Object.assign(this,e)}}Ou([Cu({type:Ll.Integer})],$I.prototype,"version",void 0),Ou([Cu({type:tp})],$I.prototype,"subject",void 0),Ou([Cu({type:Db})],$I.prototype,"subjectPKInfo",void 0),Ou([Cu({type:FI,implicit:!0,context:0})],$I.prototype,"attributes",void 0);class GI{constructor(e={}){this.certificationRequestInfo=new $I,this.signatureAlgorithm=new Nb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Ou([Cu({type:$I})],GI.prototype,"certificationRequestInfo",void 0),Ou([Cu({type:Nb})],GI.prototype,"signatureAlgorithm",void 0),Ou([Cu({type:Ll.BitString})],GI.prototype,"signature",void 0);const jI="crypto.algorithm",qI="crypto.algorithmProvider";var zI;FA.registerSingleton(qI,class{getAlgorithms(){return FA.resolveAll(jI)}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 Nb({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 WI="1.3.36.3.3.2.8.1.1",JI=`${WI}.1`,YI=`${WI}.2`,XI=`${WI}.3`,ZI=`${WI}.4`,ev=`${WI}.5`,tv=`${WI}.6`,rv=`${WI}.7`,sv=`${WI}.8`,iv=`${WI}.9`,nv=`${WI}.10`,av=`${WI}.11`,ov=`${WI}.12`,cv=`${WI}.13`,lv=`${WI}.14`,dv="brainpoolP160r1",uv="brainpoolP160t1",hv="brainpoolP192r1",fv="brainpoolP192t1",gv="brainpoolP224r1",pv="brainpoolP224t1",bv="brainpoolP256r1",mv="brainpoolP256t1",yv="brainpoolP320r1",Av="brainpoolP320t1",Iv="brainpoolP384r1",vv="brainpoolP384t1",wv="brainpoolP512r1",Sv="brainpoolP512t1",Ev="ECDSA";let Cv=zI=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Ev.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Oy;case"sha-256":return Uy;case"sha-384":return Ty;case"sha-512":return Ny}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=xy;break;case"K-256":t=zI.SECP256K1;break;case"P-384":t=_y;break;case"P-521":t=By;break;case dv:t=JI;break;case uv:t=YI;break;case hv:t=XI;break;case fv:t=ZI;break;case gv:t=ev;break;case pv:t=tv;break;case bv:t=rv;break;case mv:t=sv;break;case yv:t=iv;break;case Av:t=nv;break;case Iv:t=av;break;case vv:t=ov;break;case wv:t=cv;break;case Sv:t=lv}if(t)return new Nb({algorithm:vy,parameters:Ru.serialize(new Hy({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case wy:return{name:Ev,hash:{name:"SHA-1"}};case Ey:return{name:Ev,hash:{name:"SHA-256"}};case Cy:return{name:Ev,hash:{name:"SHA-384"}};case ky:return{name:Ev,hash:{name:"SHA-512"}};case vy:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Ru.parse(e.parameters,Hy).namedCurve){case xy:return{name:Ev,namedCurve:"P-256"};case zI.SECP256K1:return{name:Ev,namedCurve:"K-256"};case _y:return{name:Ev,namedCurve:"P-384"};case By:return{name:Ev,namedCurve:"P-521"};case JI:return{name:Ev,namedCurve:dv};case YI:return{name:Ev,namedCurve:uv};case XI:return{name:Ev,namedCurve:hv};case ZI:return{name:Ev,namedCurve:fv};case ev:return{name:Ev,namedCurve:gv};case tv:return{name:Ev,namedCurve:pv};case rv:return{name:Ev,namedCurve:bv};case sv:return{name:Ev,namedCurve:mv};case iv:return{name:Ev,namedCurve:yv};case nv:return{name:Ev,namedCurve:Av};case av:return{name:Ev,namedCurve:Iv};case ov:return{name:Ev,namedCurve:vv};case cv:return{name:Ev,namedCurve:wv};case lv:return{name:Ev,namedCurve:Sv}}}return null}};Cv.SECP256K1="1.3.132.0.10",Cv=zI=Ou([$A()],Cv),FA.registerSingleton(jI,Cv);const kv=Symbol("name"),xv=Symbol("value");class _v{constructor(e,t={},r=""){this[kv]=e,this[xv]=r;for(const e in t)this[e]=t[e]}}_v.NAME=kv,_v.VALUE=xv;class Bv{static toString(e){return this.items[e]||e}}Bv.items={[rA]:"sha1",[sA]:"sha224",[iA]:"sha256",[nA]:"sha384",[aA]:"sha512",[Fy]:"rsaEncryption",[Wy]:"sha1WithRSAEncryption",[Jy]:"sha224WithRSAEncryption",[Yy]:"sha256WithRSAEncryption",[Xy]:"sha384WithRSAEncryption",[Zy]:"sha512WithRSAEncryption",[vy]:"ecPublicKey",[wy]:"ecdsaWithSHA1",[Sy]:"ecdsaWithSHA224",[Ey]:"ecdsaWithSHA256",[Cy]:"ecdsaWithSHA384",[ky]:"ecdsaWithSHA512",[Zp]:"TLS WWW server authentication",[eb]:"TLS WWW client authentication",[tb]:"Code Signing",[rb]:"E-mail Protection",[sb]:"Time Stamping",[ib]:"OCSP Signing",[my]:"Signed Data"};class Rv{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[_v.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[_v.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],a=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${a}${n}`);else if(n instanceof Date)r.push(`${s}${a}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[_v.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof _v)n[_v.NAME]=i,r.push(...this.serializeObj(n,t));else if(uc.isBufferSource(n))i?(r.push(`${s}${a}`),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[_v.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=uc.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)}}Rv.oidSerializer=Bv,Rv.algorithmSerializer=class{static toTextObject(e){const t=new _v("Algorithm Identifier",{},Bv.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case vy:{const r=(new Cv).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Ov{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Ru.serialize(t),this.onInit(t)}else{const t=Ru.parse(e[0],e[1]);this.rawData=uc.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Ov&&Ic(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Ru.toString(this.rawData);case"text":return Rv.serialize(this.toTextObject());case"hex":return yc.ToHex(this.rawData);case"base64":return yc.ToBase64(this.rawData);case"base64url":return yc.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 _v(this.getTextName(),{},e)}}Ov.NAME="ASN";class Uv extends Ov{constructor(...e){let t;t=uc.isBufferSource(e[0])?uc.toArrayBuffer(e[0]):Ru.serialize(new Hb({extnID:e[0],critical:e[1],extnValue:new qd(uc.toArrayBuffer(e[2]))})),super(t,Hb)}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[_v.NAME]===Uv.NAME&&(e[_v.NAME]=Bv.toString(this.type)),e}}var Tv;class Nv{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[Tv]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(Nv.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(Nv.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=Nv.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(Nv.DEFAULT,e);return this}}Tv=Symbol.toStringTag,Nv.DEFAULT="default";const Dv=new Nv,Mv=/^[0-2](?:\.[1-9][0-9]*)+$/;class Pv{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(Mv).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const Lv=new Pv;function Hv(e,t){return`\\${yc.ToHex(yc.FromUtf8String(t)).toUpperCase()}`}Lv.register("CN","2.5.4.3"),Lv.register("L","2.5.4.7"),Lv.register("ST","2.5.4.8"),Lv.register("O","2.5.4.10"),Lv.register("OU","2.5.4.11"),Lv.register("C","2.5.4.6"),Lv.register("DC","0.9.2342.19200300.100.1.25"),Lv.register("E","1.2.840.113549.1.9.1"),Lv.register("G","2.5.4.42"),Lv.register("I","2.5.4.43"),Lv.register("SN","2.5.4.4"),Lv.register("T","2.5.4.12");class Vv{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 Pv,this.asn=new tp;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 tp?this.asn=e:uc.isBufferSource(e)?this.asn=Ru.parse(e,tp):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||Lv.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)||Lv.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${yc.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Hv)}`).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?`#${yc.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new tp,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 a=s[3];e=this.getTypeOid(e);const o=this.createAttribute(e,r);"+"===i?t[t.length-1].push(o):t.push(new Zg([o])),i=a}return t}fromJSON(e){const t=new tp;for(const r of e){const e=new Zg;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 Xg({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=yc.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:Vv.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 Ru.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]||Dv.get()):r=e[0]||Dv.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const Kv="Cannot initialize GeneralName from ASN.1 data.",Qv=`${Kv} Unsupported string format in use.`,Fv=`${Kv} Value doesn't match to GUID regular expression.`,$v=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Gv="1.3.6.1.4.1.311.25.1",jv="1.3.6.1.4.1.311.20.2.3",qv="dns",zv="dn",Wv="email",Jv="ip",Yv="url",Xv="guid",Zv="upn",ew="id";class tw extends Ov{constructor(...e){let t;if(2===e.length)switch(e[0]){case zv:{const r=new Vv(e[1]).toArrayBuffer(),s=Ru.parse(r,tp);t=new np({directoryName:s});break}case qv:t=new np({dNSName:e[1]});break;case Wv:t=new np({rfc822Name:e[1]});break;case Xv:{const r=new RegExp($v,"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?yc.ToHex(new Uint8Array(yc.FromHex(e)).reverse()):e).join("");t=new np({otherName:new sp({typeId:Gv,value:Ru.serialize(new qd(yc.FromHex(s)))})});break}case Jv:t=new np({iPAddress:e[1]});break;case ew:t=new np({registeredID:e[1]});break;case Zv:t=new np({otherName:new sp({typeId:jv,value:Ru.serialize(iu.toASN(e[1]))})});break;case Yv:t=new np({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=uc.isBufferSource(e[0])?Ru.parse(e[0],np):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=qv,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=Wv,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=Jv,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=Yv,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=ew,this.value=e.registeredID;else if(null!=e.directoryName)this.type=zv,this.value=new Vv(e.directoryName).toString();else{if(null==e.otherName)throw new Error(Qv);if(e.otherName.typeId===Gv){this.type=Xv;const t=Ru.parse(e.otherName.value,qd),r=new RegExp($v,"i").exec(yc.ToHex(t));if(!r)throw new Error(Fv);this.value=r.slice(1).map((e,t)=>t<3?yc.ToHex(new Uint8Array(yc.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==jv)throw new Error(Qv);this.type=Zv,this.value=Ru.parse(e.otherName.value,Jg).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case zv:case qv:case Xv:case Jv:case ew:case Zv:case Yv:e=this.type.toUpperCase();break;case Wv:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===ew&&(t=Bv.toString(t)),new _v(e,void 0,t)}}class rw extends Ov{constructor(e){let t;if(e instanceof Ep)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof np)r.push(t);else{const e=Ru.parse(new tw(t.type,t.value).rawData,np);r.push(e)}t=new Ep(r)}else{if(!uc.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Ru.parse(e,Ep)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new tw(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[_v.NAME]];Array.isArray(s)||(s=[],e[r[_v.NAME]]=s),s.push(r)}return e}}rw.NAME="GeneralNames";const sw="-{5}",iw="\\n",nw="\\n",aw=`${sw}BEGIN ([^${iw}]+(?=${sw}))${sw}${nw}(?:((?:[^:${iw}]+: (?:[^${iw}]+${nw}(?: +[^${iw}]+${nw})*))+))?${nw}?((?:[a-zA-Z0-9=+/]+${nw})+)${sw}END \\1${sw}`;class ow{static isPem(e){return"string"==typeof e&&new RegExp(aw,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(aw,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${iw}]+`,"g"),""),t={type:s[1],headers:[],rawData:yc.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(nw,"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(!uc.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:uc.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:uc.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=yc.ToBase64(e.rawData);let n,a=0;const o=Array();for(;a<i.length&&(i.length-a<64?n=i.substring(a):(n=i.substring(a,a+64),a+=64),0!==n.length)&&(o.push(n),!(n.length<64)););return s.push(...o),s.push(`-----END ${r}-----`),s.join("\n")}}ow.CertificateTag="CERTIFICATE",ow.CrlTag="CRL",ow.CertificateRequestTag="CERTIFICATE REQUEST",ow.PublicKeyTag="PUBLIC KEY",ow.PrivateKeyTag="PRIVATE KEY";class cw extends Ov{static isAsnEncoded(e){return uc.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(ow.isPem(e))return ow.decode(e)[0];if(yc.isHex(e))return yc.FromHex(e);if(yc.isBase64(e))return yc.FromBase64(e);if(yc.isBase64Url(e))return yc.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=yc.ToBinary(e);return ow.isPem(t)?ow.decode(t)[0]:yc.isHex(t)?yc.FromHex(t):yc.isBase64(t)?yc.FromBase64(t):yc.isBase64Url(t)?yc.FromBase64Url(t):uc.toArrayBuffer(e)}}constructor(...e){cw.isAsnEncoded(e[0])?super(cw.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?ow.encode(this.rawData,this.tag):super.toString(e)}}class lw extends cw{static async create(e,t=Dv.get()){if(e instanceof lw)return e;if(Nv.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new lw(r)}if(e.publicKey)return e.publicKey;if(uc.isBufferSource(e))return new lw(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){cw.isAsnEncoded(e)?super(e,Db):super(e),this.tag=ow.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]||Dv.get()):t=e[0]||Dv.get();let i=this.rawData;const n=Ru.parse(this.rawData,Db);return n.algorithm.algorithm===jy&&(i=function(e){return e.algorithm=new Nb({algorithm:Fy,parameters:null}),Ru.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=FA.resolve(qI),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Fy:{const t=Ru.parse(e.subjectPublicKey,AA),s=uc.toUint8Array(t.modulus);r.publicExponent=uc.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]||Dv.get()):r=e[0]||Dv.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=Dv.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=Dv.get();const s=Ru.parse(this.rawData,Db);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Ru.parse(this.rawData,Db);return e.Algorithm=Rv.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===vy?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class dw extends Uv{static async create(e,t=!1,r=Dv.get()){if("name"in e&&"serialNumber"in e)return new dw(e,t);const s=await lw.create(e,r),i=await s.getKeyIdentifier(r);return new dw(yc.ToHex(i),t)}constructor(...e){if(uc.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Ip({keyIdentifier:new Ap(yc.FromHex(e[0]))});super(yp,e[1],Ru.serialize(t))}else{const t=e[0],r=t.name instanceof rw?Ru.parse(t.name.rawData,Ep):t.name,s=new Ip({authorityCertIssuer:r,authorityCertSerialNumber:yc.FromHex(t.serialNumber)});super(yp,e[1],Ru.serialize(s))}}onInit(e){super.onInit(e);const t=Ru.parse(e.extnValue,Ip);t.keyIdentifier&&(this.keyId=yc.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?yc.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ru.parse(this.value,Ip);return t.authorityCertIssuer&&(e["Authority Issuer"]=new rw(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}dw.NAME="Authority Key Identifier";class uw extends Uv{constructor(...e){if(uc.isBufferSource(e[0])){super(e[0]);const t=Ru.parse(this.value,wp);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new wp({cA:e[0],pathLenConstraint:e[1]});super(vp,e[2],Ru.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 hw,fw;uw.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"}(hw||(hw={}));class gw extends Uv{constructor(...e){if(uc.isBufferSource(e[0])){super(e[0]);const t=Ru.parse(this.value,Xp);this.usages=t.map(e=>e)}else{const t=new Xp(e[0]);super(Yp,e[1],Ru.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Bv.toString(e)).join(", "),e}}gw.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"}(fw||(fw={}));class pw extends Uv{constructor(...e){if(uc.isBufferSource(e[0])){super(e[0]);const t=Ru.parse(this.value,hb);this.usages=t.toNumber()}else{const t=new hb(e[0]);super(lb,e[1],Ru.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ru.parse(this.value,hb);return e[""]=t.toJSON().join(", "),e}}pw.NAME="Key Usages";class bw extends Uv{static async create(e,t=!1,r=Dv.get()){const s=await lw.create(e,r),i=await s.getKeyIdentifier(r);return new bw(yc.ToHex(i),t)}constructor(...e){if(uc.isBufferSource(e[0])){super(e[0]);const t=Ru.parse(this.value,xb);this.keyId=yc.ToHex(t)}else{const t="string"==typeof e[0]?yc.FromHex(e[0]):e[0],r=new xb(t);super(kb,e[1],Ru.serialize(r)),this.keyId=yc.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ru.parse(this.value,xb);return e[""]=t,e}}bw.NAME="Subject Key Identifier";class mw extends Uv{constructor(...e){uc.isBufferSource(e[0])?super(e[0]):super(vb,e[1],new rw(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Ru.parse(e.extnValue,wb);this.names=new rw(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}mw.NAME="Subject Alternative Name";class yw{static register(e,t){this.items.set(e,t)}static create(e){const t=new Uv(e),r=this.items.get(t.type);return r?new r(e):t}}yw.items=new Map;class Aw extends Uv{constructor(...e){var t;if(uc.isBufferSource(e[0])){super(e[0]);const t=Ru.parse(this.value,Dp);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new Dp(r.map(e=>new Np({policyIdentifier:e})));super(_p,s,Ru.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new _v("",{},Bv.toString(e))),e}}Aw.NAME="Certificate Policies",yw.register(_p,Aw);class Iw extends Uv{constructor(...e){var t;if(uc.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new Fp({distributionPoint:new Qp({fullName:[new np({uniformResourceIdentifier:e})]})})),r=new $p(t);super(Hp,e[1],Ru.serialize(r))}else{const t=new $p(e[0]);super(Hp,e[1],Ru.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Ru.parse(e.extnValue,$p);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 tw(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}Iw.NAME="CRL Distribution Points";class vw extends Uv{constructor(...e){var t,r,s,i;if(uc.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof mp){const t=new mp(e[0]);super(pp,e[1],Ru.serialize(t))}else{const t=e[0],r=new mp;Sw(r,t,lp,"ocsp"),Sw(r,t,dp,"caIssuers"),Sw(r,t,up,"timeStamping"),Sw(r,t,hp,"caRepository"),super(pp,e[1],Ru.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=[],Ru.parse(e.extnValue,mp).forEach(e=>{switch(e.accessMethod){case lp:this.ocsp.push(new tw(e.accessLocation));break;case dp:this.caIssuers.push(new tw(e.accessLocation));break;case up:this.timeStamping.push(new tw(e.accessLocation));break;case hp:this.caRepository.push(new tw(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&ww(e,"OCSP",this.ocsp),this.caIssuers.length&&ww(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&ww(e,"Time Stamping",this.timeStamping),this.caRepository.length&&ww(e,"CA Repository",this.caRepository),e}}function ww(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new _v("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[_v.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function Sw(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new tw("url",t)),e.push(new bp({accessMethod:r,accessLocation:Ru.parse(t.rawData,np)}))})}vw.NAME="Authority Info Access";class Ew extends Ov{constructor(...e){let t;if(uc.isBufferSource(e[0]))t=uc.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>uc.toArrayBuffer(e)):[];t=Ru.serialize(new Sb({type:r,values:s}))}super(t,Sb)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new _v("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[_v.NAME]===Ew.NAME&&(e[_v.NAME]=Bv.toString(this.type)),e}}Ew.NAME="Attribute";class Cw extends Ew{constructor(...e){var t;if(uc.isBufferSource(e[0]))super(e[0]);else{const t=new MI({printableString:e[0]});super(mI,[Ru.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Ru.parse(this.values[0],MI);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[_v.VALUE]=this.password,e}}Cw.NAME="Challenge Password";class kw extends Ew{constructor(...e){var t;if(uc.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Vb;for(const e of t)r.push(Ru.parse(e.rawData,Hb));super(yI,[Ru.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Ru.parse(this.values[0],Vb);this.items=e.map(e=>yw.create(Ru.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[_v.NAME]]=r;return e}}kw.NAME="Extensions";class xw{static register(e,t){this.items.set(e,t)}static create(e){const t=new Ew(e),r=this.items.get(t.type);return r?new r(e):t}}xw.items=new Map;const _w="crypto.signatureFormatter";var Bw;let Rw=Bw=class{static createPssParams(e,t){const r=Bw.getHashAlgorithm(e);return r?new fA({hashAlgorithm:r,maskGenAlgorithm:new Nb({algorithm:oA,parameters:Ru.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=FA.resolve(qI);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 Nb({algorithm:Fy,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 Nb({algorithm:Wy,parameters:null});case"sha-256":return new Nb({algorithm:Yy,parameters:null});case"sha-384":return new Nb({algorithm:Xy,parameters:null});case"sha-512":return new Nb({algorithm:Zy,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=Bw.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Nb({algorithm:jy,parameters:Ru.serialize(t)})}return new Nb({algorithm:jy,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Fy:return{name:"RSASSA-PKCS1-v1_5"};case Wy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Yy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Xy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Zy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case jy:if(e.parameters){const t=Ru.parse(e.parameters,fA);return{name:"RSA-PSS",hash:FA.resolve(qI).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Rw=Bw=Ou([$A()],Rw),FA.registerSingleton(jI,Rw);let Ow=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Nb({algorithm:rA});case"sha-256":return new Nb({algorithm:iA});case"sha-384":return new Nb({algorithm:nA});case"sha-512":return new Nb({algorithm:aA})}return null}toWebAlgorithm(e){switch(e.algorithm){case rA:return{name:"SHA-1"};case iA:return{name:"SHA-256"};case nA:return{name:"SHA-384"};case aA:return{name:"SHA-512"}}return null}};Ow=Ou([$A()],Ow),FA.registerSingleton(jI,Ow);class Uw{addPadding(e,t){const r=uc.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=uc.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=Uw.namedCurveSize.get(r)||Uw.defaultNamedCurveSize,i=new Ky,n=uc.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Ru.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Ru.parse(t,Ky),s=e.namedCurve,i=Uw.namedCurveSize.get(s)||Uw.defaultNamedCurveSize;return Ac(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}Uw.namedCurveSize=new Map,Uw.defaultNamedCurveSize=32;const Tw="1.3.101.110",Nw="1.3.101.111",Dw="1.3.101.112",Mw="1.3.101.113";let Pw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=Dw;break;case"x25519":t=Tw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=Dw;break;case"ed448":t=Mw}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Tw;break;case"x448":t=Nw}}return t?new Nb({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case Dw:return{name:"Ed25519"};case Mw:return{name:"EdDSA",namedCurve:"Ed448"};case Tw:return{name:"X25519"};case Nw:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Pw=Ou([$A()],Pw),FA.registerSingleton(jI,Pw);(class extends cw{constructor(e){cw.isAsnEncoded(e)?super(e,GI):super(e),this.tag=ow.CertificateRequestTag}onInit(e){this.tbs=Ru.serialize(e.certificationRequestInfo),this.publicKey=new lw(e.certificationRequestInfo.subjectPKInfo);const t=FA.resolve(qI);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>xw.create(Ru.serialize(e)));const r=this.getAttribute(yI);this.extensions=[],r instanceof kw&&(this.extensions=r.items),this.subjectName=new Vv(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=Dv.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=FA.resolveAll(_w).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=Ru.parse(this.rawData,GI),r=t.certificationRequestInfo,s=new _v("",{Version:`${Kb[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new _v("");for(const t of this.attributes){const r=t.toTextObject();e[r[_v.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new _v("",{Algorithm:Rv.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class Lw extends cw{constructor(e){cw.isAsnEncoded(e)?super(e,Fb):super(e),this.tag=ow.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Ru.serialize(t),this.serialNumber=yc.ToHex(t.serialNumber),this.subjectName=new Vv(t.subject),this.subject=new Vv(t.subject).toString(),this.issuerName=new Vv(t.issuer),this.issuer=this.issuerName.toString();const r=FA.resolve(qI);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=>yw.create(Ru.serialize(e)))),this.publicKey=new lw(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=Dv.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 lw)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(uc.isBufferSource(i)){const e=new lw(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=FA.resolveAll(_w).reverse();let a=null;for(const e of n)if(a=e.toWebSignature(r,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const o=await t.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return o;{const t=(e.date||new Date).getTime();return o&&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=Dv.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=Dv.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Ru.parse(this.rawData,Fb),r=t.tbsCertificate,s=new _v("",{Version:`${Kb[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Rv.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new _v("",{"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 _v("");for(const t of this.extensions){const r=t.toTextObject();e[r[_v.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new _v("",{Algorithm:Rv.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}Lw.NAME="Certificate";class Hw{static async createSelfSigned(e,t=Dv.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=Dv.get()){var r;let s;s=e.publicKey instanceof lw?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:uc.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const i=e.serialNumber?uc.toUint8Array(yc.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));i[0]>127&&(i[0]&=127),i.length>1&&0===i[0]&&(i[1]|=128);const n=e.notBefore||new Date,a=e.notAfter||new Date(n.getTime()+31536e6),o=new Fb({tbsCertificate:new Qb({version:Kb.v3,serialNumber:i,validity:new Pb({notBefore:n,notAfter:a}),extensions:new Vb((null===(r=e.extensions)||void 0===r?void 0:r.map(e=>Ru.parse(e.rawData,Hb)))||[]),subjectPublicKeyInfo:Ru.parse(s,Db)})});if(e.subject){const t=e.subject instanceof Vv?e.subject:new Vv(e.subject);o.tbsCertificate.subject=Ru.parse(t.toArrayBuffer(),tp)}if(e.issuer){const t=e.issuer instanceof Vv?e.issuer:new Vv(e.issuer);o.tbsCertificate.issuer=Ru.parse(t.toArrayBuffer(),tp)}const c={hash:"SHA-256"},l="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},d=FA.resolve(qI);o.tbsCertificate.signature=o.signatureAlgorithm=d.toAsnAlgorithm(l);const u=Ru.serialize(o.tbsCertificate),h="signingKey"in e?await t.subtle.sign(l,e.signingKey,u):e.signature,f=FA.resolveAll(_w).reverse();let g=null;for(const e of f)if(g=e.toAsnSignature(l,h),g)break;if(!g)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return o.signatureValue=g,new Lw(Ru.serialize(o))}}var Vw;!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={})),yw.register(vp,uw),yw.register(Yp,gw),yw.register(lb,pw),yw.register(kb,bw),yw.register(yp,dw),yw.register(vb,mw),yw.register(Hp,Iw),yw.register(pp,vw),xw.register(mI,Cw),xw.register(yI,kw),FA.registerSingleton(_w,class{toAsnSignature(e,t){return uc.toArrayBuffer(t)}toWebSignature(e,t){return uc.toArrayBuffer(t)}}),FA.registerSingleton(_w,Uw),Uw.namedCurveSize.set("P-256",32),Uw.namedCurveSize.set("K-256",32),Uw.namedCurveSize.set("P-384",48),Uw.namedCurveSize.set("P-521",66);const Kw=Xs.new(void 0,"net"),Qw=new class extends Af{constructor(){super(...arguments),this.subtle=new Gg}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=Ef.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return kf().randomFillSync(t),e}};Dv.set(Qw);const Fw="Ed25519",$w="OKP";var Gw,jw,qw;function zw(e){return`e${function(e){function t(t){const r=t>>3,s=t%8;return(e.at(r)??0)>>s&1}const r=[];for(let s=0;s<8*e.length;s+=5){let e=0;for(let r=s+4;r>=s;r--)e<<=1,e|=t(r);r.push("abcdefghijklmnopqrstuvwxyz234567"[e])}return r.join("")}(e.raw)}`}function Ww(e){const t=new Uint8Array(Buffer.from(e.x??"","base64url"));return zw(P.blobFrom(t))}async function Jw(e,t){if(e.kty!==$w)throw new Error(`Unsupported key type ${e.kty}`);const r={name:"EdDSA",namedCurve:Fw};return await Qw.subtle.importKey("jwk",e,r,!0,[t===jw.Public?"verify":"sign"])}function Yw(e){return`${e.toString("pem")}\n`}function Xw(e){return{key:Zw(e._privKey.raw),ops:{async sign(e,t){const r=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return Zw((await vr(r,P.blobFrom(new Uint8Array(t)))).raw)},async verify(e,t,r){const s=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return(await wr([{signature:L.fromBlob(new Uint8Array(r),yr).asOpaque(),key:s.pubKey,message:P.blobFrom(new Uint8Array(t))}]))[0]}}}}function Zw(e){if(e.buffer instanceof ArrayBuffer)return e.buffer;const t=new ArrayBuffer(e.length);return new Uint8Array(t).set(e,0),t}function eS(){const e={info:null,verifyCallback:async(t,r)=>{const s=await async function(e){if(Kw.log("Incoming peer. Verifying certificate"),1!==e.length)return Kw.log("Rejecting peer with no certificates."),D.error(Gw.NoCertificate);const t=new(dc().X509Certificate)(e[0]);if(t.publicKey.asymmetricKeyType!==Fw.toLowerCase())return Kw.log(`Rejecting peer using non-ed25519 certificate: ${t.publicKey.asymmetricKeyType}`),D.error(Gw.NotEd25519);const r=t.publicKey.export({format:"jwk"});if(r.kty!==$w||r.crv!==Fw)return Kw.log(`Public key type mismatch: ${r.kty}, ${r.crv}`),D.error(Gw.PublicKeyTypeMismatch);const s=Ww(r),i=(t.subjectAltName??"").match(/DNS:([^,]+)/);if(null===i||i[1]!==s)return Kw.log(`AltName mismatch. Expected: '${s}', got: '${i?.[1]}'`),D.error(Gw.AltNameMismatch);const n=Buffer.from(r.x??"","base64url");if(!t.verify(t.publicKey))return D.error(Gw.IncorrectSignature);const a=L.fromBlob(new Uint8Array(n),mr);return D.ok({id:s,key:a.asOpaque()})}(t);if(s.isError)return function(e){if(void 0===e)return e;switch(e){case Gw.AltNameMismatch:return Yo.IllegalParameter;case Gw.NotEd25519:return Yo.InsufficientSecurity;case Gw.PublicKeyTypeMismatch:return Yo.BadCertificate;case Gw.NoCertificate:return Yo.CertificateRequired;case Gw.IncorrectSignature:return Yo.BadCertificate;default:throw new Error(`Unexpected VerifyCertError: ${e}`)}}(s.error);e.info=s.ok}};return e}!function(e){e[e.NoCertificate=0]="NoCertificate",e[e.NotEd25519=1]="NotEd25519",e[e.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",e[e.AltNameMismatch=3]="AltNameMismatch",e[e.IncorrectSignature=4]="IncorrectSignature"}(Gw||(Gw={})),function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(jw||(jw={})),function(e){e[e.LocalClose=0]="LocalClose",e[e.RemoteClose=1]="RemoteClose",e[e.Exception=2]="Exception"}(qw||(qw={}));const tS=Xs.new(void 0,"peers");function rS(e){return`${e.id}@${e.address.host}:${e.address.port}`}class sS{_onPeerConnected=[];_onPeerDisconnected=[];peers=new Map;peerConnected(e){tS.info(`💡 Peer ${rS(e)} connected.`),void 0!==this.peers.get(e.id)&&tS.warn("Replacing older connection."),this.peers.set(e.id,e);for(const t of this._onPeerConnected)t(e)}peerDisconnected(e){tS.info(`⚡︎Peer ${rS(e)} disconnected.`),this.peers.delete(e.id);for(const t of this._onPeerDisconnected)t(e)}isConnected(e){return this.peers.has(e)}noOfConnectedPeers(){return this.peers.size}onPeerConnected(e){return this._onPeerConnected.push(e),()=>{const t=this._onPeerConnected.indexOf(e);-1!==t&&this._onPeerConnected.splice(t,1)}}onPeerDisconnected(e){return this._onPeerDisconnected.push(e),()=>{const t=this._onPeerDisconnected.indexOf(e);-1!==t&&this._onPeerDisconnected.splice(t,1)}}}const iS=Xs.new(void 0,"net");class nS{socket;server;_dial;_peers;listen;started=!1;constructor(e,t,r,s,i){this.socket=e,this.server=t,this._dial=r,this._peers=s,this.listen=i}get isRunning(){return this.started}async start(){if(this.started)throw new Error("Network already started!");this.started=!0,await this.socket.start({host:this.listen.host,port:this.listen.port}),iS.info(`🛜 QUIC socket on ${this.socket.host}:${this.socket.port}`),await this.server.start(),iS.log("🛜 QUIC server listening")}async stop(){if(!this.started)throw new Error("Network not started yet!");iS.info("Stopping the networking."),await this.server.stop(),await this.socket.stop(),this.started=!1,iS.info("Networking stopped.")}get peers(){return this._peers}async dial(e,t={}){return this._dial(e,t)}}const aS=Xs.new(void 0,"net");function oS(e,t,r){e.addEventListener(t.name,async e=>{try{await r(e)}catch(e){aS.error(`Unhandled exception in ${t.name} event handler: ${e}`)}})}class cS{stream;constructor(e){this.stream=e}get streamId(){return this.stream.streamId}get readable(){return this.stream.readable}get writable(){return this.stream.writable}addOnError(e){oS(this.stream,ko,t=>{const r=t.detail instanceof Ra||t.detail instanceof Oa||t.detail instanceof wa,s=t.detail instanceof Ea,i=r?qw.LocalClose:s?qw.RemoteClose:qw.Exception;e(t.detail,i)})}destroy(){return this.stream.destroy()}}const lS=Xs.new(void 0,"peers");class dS{conn;connectionId;address;id;key;streamEvents=new(Gn());constructor(e,t){this.conn=e,lS.log(`👥 [${t.id}] peer connected ${e.remoteHost}:${e.remotePort}`),this.connectionId=e.connectionIdShared.toString(),this.address={host:e.remoteHost,port:e.remotePort},this.id=t.id,this.key=t.key,oS(e,wo,e=>{const t=e.detail;lS.log(`🚰 [${this.id}] new stream: [${t.streamId}]`),this.streamEvents.emit("stream",new cS(t))}),oS(e,Io,e=>{lS.error(`❌ [${this.id}] connection failed: ${e.detail}`)})}addOnIncomingStream(e){this.streamEvents.on("stream",e)}openStream(){const e=this.conn.newStream("bidi");return lS.log(`🚰 [${this.id}] opening stream: [${e.streamId}]`),new cS(e)}async disconnect(){lS.log(`👋 [${this.id}] disconnecting`),await this.conn.stop({isApp:!0})}}const uS=Xs.new(void 0,"net");class hS{static async setup({host:e,port:t,protocols:r,key:s}){const i=Xs.getLevel("net")>Fs.TRACE?Zs.WARN:Zs.DEBUG,n=new mi("quic",i,[new Ai(hi`${ni}:${oi}:${li}`)]),a=function(e){const t={kty:$w,crv:Fw,x:Buffer.from(e.pubKey.raw).toString("base64url"),d:Buffer.from(e._privKey.raw).toString("base64url")};return{publicKey:{...t,d:void 0},privateKey:{...t,x:void 0}}}(s),o=await async function(e){const t=await Jw(e.privateKey,jw.Private),r=await Qw.subtle.exportKey("pkcs8",t);return["-----BEGIN PRIVATE KEY-----",...Buffer.from(r).toString("base64").match(/.{1,64}/g)??[],"-----END PRIVATE KEY-----",""].join("\n")}(a),c=await async function({certId:e,subjectKeyPair:t,issuerKeyPair:r,subjectAttrsExtra:s=[],issuerAttrsExtra:i=[],now:n=new Date}){const a=await Jw(t.publicKey,jw.Public),o=await Jw(t.privateKey,jw.Private),c=await Jw(r.privateKey,jw.Private),l=await Jw(r.publicKey,jw.Public),d=new Date(n.getTime()-n.getTime()%1e3),u=new Date(n.getTime()-n.getTime()%1e3+2e3),h=await Qw.subtle.digest("SHA-256",await Qw.subtle.exportKey("spki",a)),f=await Qw.subtle.digest("SHA-256",await Qw.subtle.exportKey("spki",l)),g=e.toString().substring(2),p=Buffer.from(h).toString("hex"),b=Buffer.from(f).toString("hex"),m={serialNumber:g,notBefore:d,notAfter:u,subject:[{CN:[p]},...s.filter(e=>!("CN"in e))],issuer:[{CN:[b]},...i.filter(e=>!("CN"in e))],signingAlgorithm:c.algorithm,publicKey:a,signingKey:o,extensions:[new uw(!0),new pw(fw.keyCertSign|fw.cRLSign|fw.digitalSignature|fw.nonRepudiation|fw.keyAgreement|fw.keyEncipherment|fw.dataEncipherment),new gw([]),new mw([{type:"dns",value:Ww(t.publicKey)}]),await bw.create(a)]};return m.signingKey=c,await Hw.create(m)}({certId:P.blobFromString("QUIC Networking"),subjectKeyPair:a,issuerKeyPair:a}),l=eS(),d={keepAliveIntervalTime:3e3,maxIdleTimeout:6e3,applicationProtos:r,cert:Yw(c),key:o,verifyPeer:!0,verifyCallback:l.verifyCallback};uS.info(`🆔 Peer id: ** ${zw(s.pubKey)}@${e}:${t} ** (pubkey: ${s.pubKey})`);const u=new Uo({logger:n.getChild("socket")}),h=new nc({socket:u,config:d,crypto:Xw(s),logger:n.getChild("server")}),f=new sS;function g(e,t){const r=new dS(e,t);return oS(r.conn,vo,()=>f.peerDisconnected(r)),f.peerConnected(r),r}return oS(h,bo,e=>uS.error(`🛜 Server error: ${e}`)),oS(h,mo,e=>uS.error(`🛜 Server stopped: ${e}`)),oS(h,po,async e=>{const t=e.detail;if(null!==l.info){if(l.info.key.isEqualTo(s.pubKey))return uS.log(`🛜 Rejecting connection from ourself from ${t.remoteHost}:${t.remotePort}`),void await t.stop();if(f.isConnected(l.info.id))return uS.log(`🛜 Rejecting duplicate connection with peer ${l.info.id} from ${t.remoteHost}:${t.remotePort}`),void await t.stop();uS.log(`🛜 Server handshake with ${t.remoteHost}:${t.remotePort}`),g(t,l.info),l.info=null,await t.start()}else await t.stop()}),new nS(u,h,async function(e,t){const r=eS(),s=cc.createQUICClient({socket:u,host:e.host,port:e.port,crypto:{ops:{async randomBytes(e){lc.webcrypto.getRandomValues(new Uint8Array(e))}}},config:{...d,verifyCallback:r.verifyCallback},logger:n.getChild("client")},{signal:t.signal}),i=await s;if(oS(i,fo,()=>{uS.log("⚰️ Client connection closed.")}),oS(i,uo,e=>{uS.error(`🔴 Client error: ${e.detail}`)}),null===r.info)throw new Error("Client connected, but there is no peer details!");if(void 0!==t.verifyName&&t.verifyName!==r.info.id)throw new Error(`Client connected, but the id didn't match. Expected: ${t.verifyName}, got: ${r.info.id}`);return uS.log(`🤝 Client handshake with: ${e.host}:${e.port}`),g(i.connection,r.info)},f,{host:e,port:t})}}const fS=t(import.meta.url)("node:buffer");function gS(e){return de(ne(e.length))}function pS(e,t){let r=fS.Buffer.alloc(0),s=-1;return i=>{r=fS.Buffer.concat([r,i]);do{if(-1===s){if(r.length<4)break;s=r.readUint32LE(),r=r.subarray(4)}if(r.length<s)break;if(r.length>16777216){t();break}const i=r.subarray(0,s);r=r.subarray(s),s=-1,e(new Uint8Array(i))}while(r.length>0)}}class bS{id;ip;port;constructor(e,t,r){this.id=e,this.ip=t,this.port=r}get host(){return this.ip}toString(){return`${this.id}@${this.ip}:${this.port}`}}const mS=Xs.new(void 0,"net:conn");class yS{network;peerInfo=new Map;constructor(e){this.network=e,e.peers.onPeerConnected(e=>(this.updatePeer(e),O)),e.peers.onPeerDisconnected(e=>(this.scheduleReconnect(e.id),O))}setAuxData(e,t,r){this.peerInfo.get(e)?.aux.set(t.id,r)}getAuxData(e,t){return this.peerInfo.get(e)?.aux.get(t.id)}withAuxData(e,t,r){const s=r(this.getAuxData(e,t));this.setAuxData(e,t,s)}getPeerCount(){return this.network.peers.noOfConnectedPeers()}*getConnectedPeers(){for(const e of this.peerInfo.values())null!==e.peerRef&&(yield e)}updatePeer(e){const t=this.peerInfo.get(e.id);void 0!==t?(t.peerRef=e,t.lastConnected=Date.now(),t.currentRetry=Math.floor(t.currentRetry/2),t.address=e.address):this.peerInfo.set(e.id,{peerId:e.id,address:e.address,peerRef:e,lastConnected:Date.now(),maxRetries:5,currentRetry:0,backgroundTask:new AbortController,aux:new Map})}async scheduleReconnect(e){const t=this.peerInfo.get(e);if(void 0===t)return;t.peerRef=null,t.backgroundTask=new AbortController;const r=t.backgroundTask.signal;for(;;){if(t.currentRetry+=1,t.currentRetry>=t.maxRetries)return this.peerInfo.delete(e),void mS.log(`[${e}] max retries reached. Removing peer.`);const s=Math.min(3*t.currentRetry*t.currentRetry,3600);try{await(0,Qs.setTimeout)(1e3*s,void 0,{signal:r})}catch{return}if(null!==t.peerRef)return;try{return mS.trace(`[${e}] Attempting to connect to peer at ${t.address.host}:${t.address.port}.`),void await this.network.dial(t.address,{signal:r,verifyName:t.peerId})}catch{if(r.aborted)return;mS.trace(`[${e}] attempt failed. Will retry (${t.currentRetry}/${t.maxRetries})`)}}}addPersistentRetry(e){for(const t of e)this.peerInfo.set(t.id,{peerId:t.id,address:{host:t.host,port:t.port},maxRetries:2**32,currentRetry:0,peerRef:null,lastConnected:0,backgroundTask:new AbortController,aux:new Map}),this.scheduleReconnect(t.id)}}function AS(e){return te(e)}function IS(e,t){return e().catch(t)}const vS=Xs.new(void 0,"stream");class wS{incomingHandlers=new Map;outgoingHandlers=new Map;streams=new Map;backgroundTasks=new Map;registerIncomingHandlers(...e){for(const t of e)this.incomingHandlers.set(t.kind,t)}registerOutgoingHandlers(...e){for(const t of e)this.outgoingHandlers.set(t.kind,t)}getPeer(e){return this.streams.get(e)?.peer??null}async waitForFinish(){for(const e of this.backgroundTasks.values())await e}withStreamOfKind(e,t,r){for(const s of this.streams.values())if(s.handler.kind===t&&s.peer.id===e)return void r(s.handler,s.streamSender)}withNewStream(e,t,r){const s=this.outgoingHandlers.get(t);if(void 0===s)throw new Error(`Unsupported outgoing stream kind: ${t}`);const i=e.openStream(),n=this.registerStream(e,s,i,P.empty());n.bufferAndSend(P.blobFromNumbers([t]),!1),r(s,n)}async onIncomingStream(e,t){const{readable:r,streamId:s}=t,i=r.getReader();let n=P.empty();try{const t=await i.read();n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array),vS.trace(`🚰 --\x3e [${e.id}:${s}] Initial data: ${n}`)}finally{i.releaseLock()}if(n.raw.length<1)throw new Error(`Expected 1-byte stream identifier, got: ${n}`);const a=AS(n.raw[0]),o=this.incomingHandlers.get(a);if(void 0===o)throw new Error(`Unsupported stream kind: ${a}`);vS.log(`🚰 --\x3e [${e.id}:${t.streamId}] Stream identified as: ${a}`),this.registerStream(e,o,t,P.blobFrom(n.raw.subarray(1)))}registerStream(e,t,r,s){const i=(n=r.streamId,ne(n));var n;const a=(r,s)=>{this.streams.delete(i),this.backgroundTasks.delete(i),s===qw.Exception&&vS.error(`🚰 --- [${e.id}:${i}] Stream error: ${r}. Disconnecting peer.`),s!==qw.LocalClose&&(t.onClose(i,!0),e.disconnect())};r.addOnError(a);const o=new SS(i,r,a);this.streams.set(i,{handler:t,streamSender:o,peer:e});const c=IS(()=>async function(e,t,r,s,i){let n=s,a=!1;const o=pS(s=>{const i=P.blobFrom(new Uint8Array(s));vS.trace(`🚰 --\x3e [${e.id}:${r.streamId}] ${i}`),t.onStreamMessage(r,i)},()=>{vS.error(`🚰 --\x3e [${e.id}:${r.streamId}] got too much data. Disconnecting.`),e.disconnect()});for(;;){if(o(n.raw),a)return void vS.log(`🚰 --\x3e [${e.id}:${r.streamId}] remote finished.`);const t=await i.read();a=t.done,n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array)}}(e,t,o,s,r.readable.getReader()),e=>a(e,qw.Exception));return this.streams.has(i)&&this.backgroundTasks.set(i,c),o}}class SS{streamId;internal;onError;bufferedLength=0;bufferedData=[];currentWriterPromise=null;constructor(e,t,r){this.streamId=e,this.internal=t,this.onError=r}bufferAndSend(e,t=!0){return!(this.bufferedLength>16384||(this.bufferedData.push({data:e,addPrefix:t}),this.bufferedLength+=e.length,null!==this.currentWriterPromise||(this.currentWriterPromise=IS(async()=>{const e=this.internal.writable.getWriter();try{for(;;){const t=this.bufferedData.shift();if(void 0===t)return;const{data:r,addPrefix:s}=t;vS.trace(`🚰 <-- [${this.streamId}] write: ${r}`),s&&await e.write(gS(r.raw)),await e.write(r.raw),this.bufferedLength-=r.length}}finally{e.releaseLock(),this.currentWriterPromise=null}},e=>this.onError(e,qw.Exception))),0))}close(){IS(async()=>{vS.trace(`🚰 <-- [${this.streamId}] closing`),null!==this.currentWriterPromise&&await this.currentWriterPromise,await this.internal.writable.close()},e=>this.onError(e,qw.Exception))}flush(){return this.currentWriterPromise??Promise.resolve()}}const ES=AS(128);var CS;!function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(CS||(CS={}));class kS extends _{headerHash;direction;maxBlocks;static Codec=_e.Class(kS,{headerHash:_e.bytes(Pe).asOpaque(),direction:_e.u8.convert(e=>te(e),e=>{switch(e){case CS.AscExcl:return CS.AscExcl;case CS.DescIncl:return CS.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:_e.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new kS(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}const xS=Xs.new(void 0,"protocol/ce-128");class _S{chainSpec;getBlockSequence;kind=ES;constructor(e,t){this.chainSpec=e,this.getBlockSequence=t}onStreamMessage(e,t){const r=fe.decodeObject(kS.Codec,t);xS.log(`[${e.streamId}] Client has requested: ${r}`);const s=this.getBlockSequence(e.streamId,r.headerHash,r.direction,r.maxBlocks);e.bufferAndSend(Ae.encodeObject(_e.sequenceFixLen(ms.Codec.View,s.length),s,this.chainSpec)),e.close()}onClose(){}}class BS{chainSpec;kind=ES;promiseResolvers=new Map;promiseRejectors=new Map;constructor(e){this.chainSpec=e}onStreamMessage(e,t){if(!this.promiseResolvers.has(e.streamId))throw new Error("Received an unexpected message from the server.");const r=fe.decodeSequence(ms.Codec.View,t,this.chainSpec);xS.log(`[${e.streamId}] Server returned ${r.length} blocks in ${t.length} bytes of data.`),this.promiseResolvers.get(e.streamId)?.(r),this.promiseResolvers.delete(e.streamId)}onClose(e){this.promiseRejectors.get(e)?.("Stream closed."),this.promiseResolvers.delete(e),this.promiseRejectors.delete(e)}async requestBlockSequence(e,t,r,s){if(this.promiseResolvers.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");return new Promise((i,n)=>{this.promiseResolvers.set(e.streamId,i),this.promiseRejectors.set(e.streamId,n),e.bufferAndSend(Ae.encodeObject(kS.Codec,kS.create({headerHash:t,direction:r,maxBlocks:s}))),e.close()})}}var RS;!function(e){e[e.NoStartBlock=0]="NoStartBlock",e[e.BlockOnFork=1]="BlockOnFork"}(RS||(RS={}));const OS=AS(0);class US extends _{hash;slot;static Codec=_e.Class(US,{hash:_e.bytes(Pe).asOpaque(),slot:_e.u32.asOpaque()});static create({hash:e,slot:t}){return new US(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class TS{final;leafs;static Codec=_e.Class(TS,{final:US.Codec,leafs:_e.sequenceVarLen(US.Codec)});static create({final:e,leafs:t}){return new TS(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class NS extends _{header;final;static Codec=_e.Class(NS,{header:us.Codec,final:US.Codec});static create({header:e,final:t}){return new NS(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const DS=Xs.new(void 0,"protocol/up-0");class MS{spec;getHandshake;onAnnouncement;onHandshake;kind=OS;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t,r,s){this.spec=e,this.getHandshake=t,this.onAnnouncement=r,this.onHandshake=s}onStreamMessage(e,t){const{streamId:r}=e;if(!this.handshakes.has(r)){const s=fe.decodeObject(TS.Codec,t);return this.handshakes.set(r,s),this.pendingHandshakes.delete(r)||(DS.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Ae.encodeObject(TS.Codec,this.getHandshake()))),void this.onHandshake(r,s)}const s=fe.decodeObject(NS.Codec,t,this.spec);DS.log(`[${r}] --\x3e got blocks announcement: ${s.final}`),this.onAnnouncement(r,s)}onClose(e){this.handshakes.delete(e),this.pendingHandshakes.delete(e)}sendHandshake(e){const{streamId:t}=e;if(this.handshakes.has(t)||this.pendingHandshakes.has(t))return;const r=this.getHandshake();DS.trace(`[${t}] <-- sending handshake`),this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(Ae.encodeObject(TS.Codec,r))}sendAnnouncement(e,t){const{streamId:r}=e;this.handshakes.has(r)?(DS.trace(`[${r}] <-- sending block announcement: ${t.final}`),e.bufferAndSend(Ae.encodeObject(NS.Codec,t,this.spec))):DS.warn(`[${r}] <-- no handshake yet, skipping announcement.`)}}const PS=31;var LS;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(LS||(LS={}));class HS{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?LS.EmbedLeaf:LS.Leaf:LS.Branch}asBranchNode(){return w(this.getNodeType()===LS.Branch),new VS(this)}asLeafNode(){return w(this.getNodeType()!==LS.Branch),new KS(this)}toString(){return P.blobFrom(this.raw).toString()}}class VS{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new HS;return r.raw.set(e.raw,0),r.raw.set(t.raw,Pe),r.raw[0]&=127,new VS(r)}getLeft(){return L.fromBlob(this.node.raw.subarray(0,Pe),Pe).asOpaque()}getRight(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}}class KS{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new HS;return t.length<=Pe?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,PS),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,PS),1),s.raw.set(r().raw,32)),new KS(s)}getKey(){return L.fromBlob(this.node.raw.subarray(1,32),PS).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===LS.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return P.blobFrom(this.node.raw.subarray(Pe,Pe+e))}getValueHash(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}const QS=AS(129),FS=_e.bytes(64).convert(e=>L.fromBlob(e.raw,64),e=>new HS(e.raw));class $S extends _{key;value;static Codec=_e.Class($S,{key:_e.bytes(PS),value:_e.blob});static create({key:e,value:t}){return new $S(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class GS extends _{keyValuePairs;static Codec=_e.Class(GS,{keyValuePairs:_e.sequenceVarLen($S.Codec)});static create({keyValuePairs:e}){return new GS(e)}constructor(e){super(),this.keyValuePairs=e}}class jS extends _{headerHash;startKey;endKey;maximumSize;static Codec=_e.Class(jS,{headerHash:_e.bytes(Pe).asOpaque(),startKey:_e.bytes(PS),endKey:_e.bytes(PS),maximumSize:_e.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new jS(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const qS=Xs.new(void 0,"protocol/ce-129");class zS{isServer;getBoundaryNodes;getKeyValuePairs;kind=QS;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(qS.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=fe.decodeObject(jS.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return qS.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Ae.encodeObject(_e.sequenceVarLen(FS),s)),e.bufferAndSend(Ae.encodeObject(GS.Codec,GS.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,fe.decodeObject(_e.sequenceVarLen(FS),t)),void qS.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(fe.decodeObject(GS.Codec,t)),qS.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(Ae.encodeObject(jS.Codec,jS.create({headerHash:t,startKey:r,endKey:r,maximumSize:ne(4096)}))),e.close()}}AS(131),AS(132);class WS extends _{epochIndex;ticket;static Codec=_e.Class(WS,{epochIndex:_e.u32.asOpaque(),ticket:Rt.Codec});static create({epochIndex:e,ticket:t}){return new WS(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}Xs.new(void 0,"protocol/ce-131-ce-132"),AS(133);class JS extends _{coreIndex;workPackage;static Codec=_e.Class(JS,{coreIndex:_e.u16.asOpaque(),workPackage:Wr.Codec});static create({coreIndex:e,workPackage:t}){return new JS(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}Xs.new(void 0,"protocol/ce-133"),_e.blob,AS(134);class YS extends _{coreIndex;segmentsRootMappings;static Codec=_e.Class(YS,{coreIndex:_e.u16.asOpaque(),segmentsRootMappings:_e.sequenceVarLen(rs.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new YS(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class XS extends _{workReportHash;signature;static Codec=_e.Class(XS,{workReportHash:_e.bytes(Pe).asOpaque(),signature:_e.bytes(yr).asOpaque()});static create({workReportHash:e,signature:t}){return new XS(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}Xs.new(void 0,"protocol/ce-134"),AS(135);class ZS extends _{report;slot;signatures;static Codec=_e.Class(ZS,{report:ss.Codec,slot:_e.u32.asOpaque(),signatures:kt(e=>xt(ns.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new ZS(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}Xs.new(void 0,"protocol/ce-135");const eE={id:Symbol("sync")},tE=Xs.new(void 0,"net:sync");class rE{spec;streamManager;connections;blocks;onNewBlocks;static start(e,t,r,s,i){const n=new rE(e,t,r,s,i),a=e=>t.getPeer(e),o=new MS(e,()=>n.getUp0Handshake(),(e,t)=>{const r=a(e);null!==r&&n.onUp0Annoucement(r,t)},(e,t)=>{const r=a(e);null!==r&&n.onUp0Handshake(r,t)});return t.registerIncomingHandlers(o),t.registerIncomingHandlers(new _S(e,(e,t,r,s)=>{const i=a(e);return null!==i?n.handleGetBlockSequence(i,t,r,s):[]})),t.registerOutgoingHandlers(o),t.registerOutgoingHandlers(new BS(e)),n}othersBest;constructor(e,t,r,s,i){this.spec=e,this.streamManager=t,this.connections=r,this.blocks=s,this.onNewBlocks=i;const n=s.getBestHeaderHash(),a=s.getHeader(n);if(null===a)throw new Error(`Best header ${n} missing in the database?`);this.othersBest=US.create({hash:n,slot:a.timeSlotIndex.materialize()})}onUp0Handshake(e,t){const{hash:r,slot:s}=t.final;this.connections.withAuxData(e.id,eE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:null}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=null,e)),this.othersBest.slot<s&&(this.othersBest=t.final)}onUp0Annoucement(e,t){const{hash:r,slot:s}=t.final,i=function(e,t){const r=Ae.encodeObject(us.Codec,e,t);return new He(qe(r).asOpaque(),e)}(t.header,this.spec);tE.info(`[${e.id}] --\x3e Received new header #${t.header.timeSlotIndex}: ${i.hash}`),this.connections.withAuxData(e.id,eE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:i}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=i,e)),this.othersBest.slot<i.data.timeSlotIndex&&(this.othersBest=US.create({hash:i.hash,slot:i.data.timeSlotIndex}))}getUp0Handshake(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=t?.timeSlotIndex.materialize(),s=US.create({hash:e,slot:r??Ur(0)});return TS.create({final:s,leafs:[]})}openUp0(e){this.streamManager.withNewStream(e,OS,(e,t)=>(e.sendHandshake(t),O))}broadcastHeader(e){const t=e.data.timeSlotIndex.materialize(),r=NS.create({header:e.data.materialize(),final:US.create({hash:e.hash,slot:t})}),s=this.connections.getConnectedPeers();for(const i of s)this.streamManager.withStreamOfKind(i.peerId,OS,(s,n)=>(tE.log(`[${i.peerId}] <-- Broadcasting new header #${t}: ${e.hash}`),s.sendAnnouncement(n,r),O))}handleGetBlockSequence(e,t,r,s){const i=ne(Math.min(s,128)),n=function(e,t,r,s,i){const n=r=>{const s=t.getHeader(r),i=t.getExtrinsic(r);if(null===s||null===i)return null;const n=P.blobFromParts(s.encoded().raw,i.encoded().raw);return fe.decodeObject(ms.Codec.View,n,e)},a=n(r);if(null===a)return D.error(RS.NoStartBlock);if(s===CS.AscExcl){const e=[],s=a.header.view().timeSlotIndex.materialize();let o=t.getBestHeaderHash();for(;;){const a=t.getHeader(o);if(null===a||a.timeSlotIndex.materialize()<s)return D.error(RS.BlockOnFork);if(r.isEqualTo(o))return D.ok(e.reverse().slice(0,i).flatMap(e=>{const t=n(e);return null===t?[]:[t]}));e.push(o),o=a.parentHeaderHash.materialize()}}const o=[a];let c=a;for(let e=0;e<i;e++){const e=n(c.header.view().parentHeaderHash.materialize());if(null===e)break;o.push(e),c=e}return D.ok(o)}(this.spec,this.blocks,t,r,i);return n.isOk?n.ok:n.error===RS.BlockOnFork?(tE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} is on a fork.`),[]):n.error===RS.NoStartBlock?(tE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} missing header or extrinsic.`),[]):void E(n.error)}maintainSync(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=this.connections.getPeerCount();if(null===t)return{kind:sE.OurBestHeaderMissing};const s=t.timeSlotIndex.materialize(),i=this.othersBest,n=i.slot-s;if(tE.trace(`Our best. ${s}. Best seen: ${i.slot}`),n<1)return this.connections.getPeerCount(),tE.trace(`No new blocks. ${r} peers.`),{kind:sE.NoNewBlocks,ours:s,theirs:i.slot};const a=[];tE.log(`Sync ${n} blocks from ${r} peers.`);for(const e of this.connections.getConnectedPeers()){const t=this.connections.getAuxData(e.peerId,eE);if(void 0===t||null===e.peerRef)continue;const r=null!==t.bestHeader?t.bestHeader.data.timeSlotIndex:t.finalBlockSlot,i=null!==t.bestHeader?t.bestHeader.hash:t.finalBlockHash;r<=s||(a.push({peerId:e.peerId,theirs:r,count:r-s}),this.streamManager.withNewStream(e.peerRef,ES,(t,n)=>(IS(async()=>{tE.log(`Fetching blocks from ${e.peerId}.`);const a=await t.requestBlockSequence(n,i,CS.DescIncl,ne(r-s));a.reverse(),this.onNewBlocks(a,e.peerId)},t=>{tE.warn(`[${e.peerId}] --\x3e requesting blocks to import: ${t}`)}),O)))}return{kind:sE.BlocksRequested,ours:s,requested:a}}}var sE;!function(e){e[e.OurBestHeaderMissing=1]="OurBestHeaderMissing",e[e.NoNewBlocks=2]="NoNewBlocks",e[e.BlocksRequested=3]="BlocksRequested"}(sE||(sE={}));const iE=Xs.new(void 0,"jamnps");function nE(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(!ie(n))throw new Error(`Invalid port number: "${i}"`);return new bS(t,s,n)}class aE extends _{bootnodes;id;genesisHeader;genesisState;static fromJson=ee.object({bootnodes:ee.optional(ee.array(ee.fromString(nE))),id:"string",genesis_header:Tt.bytesBlobNoPrefix,genesis_state:ee.map(Tt.bytesNNoPrefix(31),Tt.bytesBlobNoPrefix)},e=>aE.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=P.empty(),genesisState:s=new Map}){return new aE({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 oE=t(import.meta.url)("node:fs");var cE=a.n(oE);const lE=t(import.meta.url)("node:os");var dE=a.n(lE);const uE=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-default","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"}'),hE=JSON.parse('{"$schema":"https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":true},"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 fE{omitSealVerification;static fromJson=ee.object({omit_seal_verification:"boolean"},fE.new);static new({omit_seal_verification:e}){return new fE(e)}constructor(e){this.omitSealVerification=e}}const gE="dev",pE="default",bE={name:dE().hostname(),config:pE};var mE;!function(e){e.Tiny="tiny",e.Full="full"}(mE||(mE={}));const yE=ee.fromString((e,t)=>{switch(e){case mE.Tiny:return mE.Tiny;case mE.Full:return mE.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class AE{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=ee.object({$schema:"string",version:"number",flavor:yE,chain_spec:aE.fromJson,database_base_path:"string",authorship:fE.fromJson},AE.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 AE(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}}const IE=t(import.meta.url)("node:worker_threads"),vE="best hash and posterior state root";class wE{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:L.fromBlob(t,Pe).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(vE,e.raw)}getBestHeaderHash(){const e=this.root.db.get(vE);return void 0===e?L.zero(Pe).asOpaque():L.fromBlob(e,Pe).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:fe.decodeObject(us.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:fe.decodeObject(bs.Codec.View,t,this.chainSpec)}}const SE=(EE={open:()=>r.open},CE={},a.d(CE,EE),CE);var EE,CE;class kE{db;constructor(e,t=!1){this.db=SE.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class xE{serviceId;output;static Codec=_e.Class(xE,{serviceId:_e.u32.asOpaque(),output:_e.bytes(Pe)});static create(e){return new xE(e.serviceId,e.output)}constructor(e,t){this.serviceId=e,this.output=t}}const _E=e=>Ce.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=qe(e.skipEncoded(r));return new He(s.asOpaque(),e.decode(t))},e.skip,e.View);class BE extends _{workReport;timeout;static Codec=_e.Class(BE,{workReport:_E(ss.Codec),timeout:_e.u32.asOpaque()});static create({workReport:e,timeout:t}){return new BE(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}function RE(e,t){return w(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const OE=e=>kt(t=>xt(e,{fixedLength:t.coresCount})),UE=()=>ke(_e.sequenceVarLen(_e.bytes(Pe))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return It.fromSortedArray(DE,t)}),TE=UE();class NE{goodSet;badSet;wonkySet;punishSet;static Codec=_e.Class(NE,{goodSet:TE,badSet:TE,wonkySet:TE,punishSet:UE()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new NE(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 NE(It.fromSortedArray(DE,e),It.fromSortedArray(DE,t),It.fromSortedArray(DE,r),It.fromSortedArray(DE,s))}}function DE(e,t){return e.compare(t)}class ME{service;gasLimit;static Codec=_e.Class(ME,{service:_e.u32.asOpaque(),gasLimit:_e.u64.asOpaque()});static create({service:e,gasLimit:t}){return new ME(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class PE{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=_e.Class(PE,{manager:_e.u32.asOpaque(),authManager:v.isGreaterOrEqual(h.V0_6_7)?OE(_e.u32.asOpaque()):kt(e=>_e.u32.asOpaque().convert(e=>e[0],t=>RE(new Array(e.coresCount).fill(t),e))),validatorsManager:_e.u32.asOpaque(),autoAccumulateServices:ke(_e.sequenceVarLen(ME.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new PE(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const LE=P.blobFromString("peak");class HE{hasher;mountains;static empty(e){return new HE(e)}static fromPeaks(e,t){return new HE(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(VE.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=VE.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 L.zero(Pe).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(LE,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 VE{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new VE(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new VE(i,n)}mergeWith(e,t){return VE.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}class KE extends _{headerHash;mmr;postStateRoot;reported;static Codec=_e.Class(KE,{headerHash:_e.bytes(Pe).asOpaque(),mmr:_e.object({peaks:ke(_e.sequenceVarLen(_e.optional(_e.bytes(Pe))))}),postStateRoot:_e.bytes(Pe).asOpaque(),reported:Bt(rs.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new KE(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}class QE extends _{blocks;static Codec=_e.Class(QE,{blocks:xt(KE.Codec,{minLength:0,maxLength:8,typicalLength:8})});static create(e){return new QE(e.blocks)}constructor(e){super(),this.blocks=e}}class FE extends _{headerHash;accumulationResult;postStateRoot;reported;static Codec=_e.Class(FE,{headerHash:_e.bytes(Pe).asOpaque(),accumulationResult:_e.bytes(Pe),postStateRoot:_e.bytes(Pe).asOpaque(),reported:Bt(rs.Codec,e=>e.workPackageHash)});static create({headerHash:e,accumulationResult:t,postStateRoot:r,reported:s}){return new FE(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.accumulationResult=t,this.postStateRoot=r,this.reported=s}}class $E extends _{blocks;accumulationLog;static Codec=_e.Class($E,{blocks:xt(FE.Codec,{minLength:0,maxLength:8,typicalLength:8}),accumulationLog:_e.object({peaks:ke(_e.sequenceVarLen(_e.optional(_e.bytes(Pe))))})});static create(e){return new $E(e.blocks,e.accumulationLog)}constructor(e,t){super(),this.blocks=e,this.accumulationLog=t}}class GE extends _{current;legacy;static Codec=Ce.new("RecentBlocksHistory",v.isGreaterOrEqual(h.V0_6_7)?$E.Codec.sizeHint:QE.Codec.sizeHint,(e,t)=>v.isGreaterOrEqual(h.V0_6_7)?$E.Codec.encode(e,t.asCurrent()):QE.Codec.encode(e,t.asLegacy()),e=>{if(v.isGreaterOrEqual(h.V0_6_7)){const t=$E.Codec.decode(e);return GE.create(t)}const t=QE.Codec.decode(e);return GE.legacyCreate(t)},e=>v.isGreaterOrEqual(h.V0_6_7)?$E.Codec.sizeHint:QE.Codec.sizeHint);static create(e){return new GE(e,null)}static legacyCreate(e){return new GE(null,e)}static empty(){return v.isGreaterOrEqual(h.V0_6_7)?GE.create($E.create({blocks:[],accumulationLog:{peaks:[]}})):GE.legacyCreate(QE.create({blocks:[]}))}static accumulationResult(e,{hasher:t}){return v.isGreaterOrEqual(h.V0_6_7)?e.accumulationResult:HE.fromPeaks(t,e.mmr).getSuperPeakHash()}constructor(e,t){super(),this.current=e,this.legacy=t}get blocks(){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return this.current.blocks;if(null!==this.legacy)return this.legacy.blocks;throw new Error("RecentBlocksHistory is in invalid state")}asCurrent(){if(null===this.current)throw new Error("Cannot access current RecentBlocks format");return this.current}asLegacy(){if(null===this.legacy)throw new Error("Cannot access legacy RecentBlocks format");return this.legacy}updateBlocks(e){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return GE.create($E.create({...this.current,blocks:e}));if(null!==this.legacy)return GE.legacyCreate(QE.create({blocks:e}));throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!")}}const jE=128;class qE extends _{bandersnatch;ed25519;bls;metadata;static Codec=_e.Class(qE,{bandersnatch:_e.bytes(Te).asOpaque(),ed25519:_e.bytes(mr).asOpaque(),bls:_e.bytes(Me).asOpaque(),metadata:_e.bytes(jE)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new qE(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var zE;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(zE||(zE={}));const WE=_e.bytes(Te).asOpaque();class JE extends _{kind;keys;tickets;static Codec=kt(e=>_e.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Pe*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===zE.Keys?e.sequenceFixLen(WE,t.keys):e.sequenceFixLen(Ot.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===zE.Keys){const s=t.sequenceFixLen(WE,r);return JE.keys(Vr(s,e))}if(s===zE.Tickets){const s=t.sequenceFixLen(Ot.Codec,r);return JE.tickets(Vr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==zE.Keys){if(r!==zE.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(Ot.Codec,e.epochLength)}else t.sequenceFixLen(WE,e.epochLength)}));static keys(e){return new JE(zE.Keys,e,void 0)}static tickets(e){return new JE(zE.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class YE{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=_e.Class(YE,{nextValidatorData:Hr(qE.Codec),epochRoot:_e.bytes(De).asOpaque(),sealingKeySeries:JE.Codec,ticketsAccumulator:ke(_e.sequenceVarLen(Ot.Codec)).convert(R,mt)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new YE(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}const XE={bytes:0,isExact:!0},ZE=e=>Ce.new("ignoreValue",XE,(e,t)=>{},t=>e,e=>{});class eC extends _{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;gratisStorage;storageUtilisationCount;created;lastAccumulation;parentService;static Codec=v.isGreaterOrEqual(h.V0_6_7)?_e.Class(eC,{codeHash:_e.bytes(Pe).asOpaque(),balance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Dr),onTransferMinGas:_e.u64.convert(e=>e,Dr),storageUtilisationBytes:_e.u64,gratisStorage:_e.u64,storageUtilisationCount:_e.u32,created:_e.u32.convert(e=>e,Ur),lastAccumulation:_e.u32.convert(e=>e,Ur),parentService:_e.u32.convert(e=>e,Nr)}):_e.Class(eC,{codeHash:_e.bytes(Pe).asOpaque(),balance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Dr),onTransferMinGas:_e.u64.convert(e=>e,Dr),storageUtilisationBytes:_e.u64,storageUtilisationCount:_e.u32,gratisStorage:ZE(oe(0)),created:ZE(Ur(0)),lastAccumulation:ZE(Ur(0)),parentService:ZE(Nr(0))});static create(e){return new eC(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.gratisStorage,e.storageUtilisationCount,e.created,e.lastAccumulation,e.parentService)}static calculateThresholdBalance(e,t,r){w(r===oe(0)||v.isGreaterOrEqual(h.V0_6_7),"Gratis storage cannot be non-zero before 0.6.7");const s=100n+10n*BigInt(e)+1n*t-r;return oe(s<0n?0:s>=2n**64n?2n**64n-1n:s)}constructor(e,t,r,s,i,n,a,o,c,l){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.gratisStorage=n,this.storageUtilisationCount=a,this.created=o,this.lastAccumulation=c,this.parentService=l}}class tC extends _{hash;blob;static Codec=_e.Class(tC,{hash:_e.bytes(Pe).asOpaque(),blob:_e.blob});static create({hash:e,blob:t}){return new tC(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class rC extends _{key;value;static Codec=_e.Class(rC,{key:_e.blob.convert(e=>e,e=>e),value:_e.blob});static create({key:e,value:t}){return new rC(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function sC(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class iC{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 nC,aC,oC;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(nC||(nC={}));class cC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new cC(e,{kind:nC.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new cC(e,{kind:nC.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new cC(e,{kind:nC.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case nC.Provide:return this.action.preimage.hash;case nC.Remove:return this.action.hash;case nC.UpdateOrAdd:return this.action.item.hash}throw E(this.action)}get length(){switch(this.action.kind){case nC.Provide:return ne(this.action.preimage.blob.length);case nC.Remove:return this.action.length;case nC.UpdateOrAdd:return this.action.item.length}throw E(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(aC||(aC={}));class lC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new lC(e,{kind:aC.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new lC(e,{kind:aC.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(oC||(oC={}));class dC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new dC(e,{kind:oC.Set,storage:t})}static remove({serviceId:e,key:t}){return new dC(e,{kind:oC.Remove,key:t})}get key(){return this.action.kind===oC.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===oC.Remove?null:this.action.storage.value}}const uC=v.isSuite(f.W3F_DAVXY)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.JAMDUNA,h.V0_6_7)?_e.u32.asOpaque():_e.varU32.convert(e=>ne(e),e=>Nr(e));class hC{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=_e.Class(hC,{blocks:_e.u32,tickets:_e.u32,preImages:_e.u32,preImagesSize:_e.u32,guarantees:_e.u32,assurances:_e.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new hC(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=ne(0);return new hC(e,e,e,e,e,e)}}const fC=_e.varU32.convert(e=>ne(e),e=>se(e)),gC=_e.varU64.convert(e=>oe(e),e=>Dr(e));class pC{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=_e.Class(pC,{dataAvailabilityLoad:_e.varU32,popularity:fC,imports:fC,exports:fC,extrinsicSize:_e.varU32,extrinsicCount:fC,bundleSize:_e.varU32,gasUsed:gC});static create(e){return new pC(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,a,o){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=a,this.gasUsed=o}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new pC(e,t,t,t,e,t,e,r)}}class bC{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=_e.Class(bC,{providedCount:fC,providedSize:_e.varU32,refinementCount:_e.varU32,refinementGasUsed:gC,imports:fC,exports:fC,extrinsicSize:_e.varU32,extrinsicCount:fC,accumulateCount:_e.varU32,accumulateGasUsed:gC,onTransfersCount:_e.varU32,onTransfersGasUsed:gC});static create(e){return new bC(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,a,o,c,l,d,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=a,this.extrinsicCount=o,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=d,this.onTransfersGasUsed=u}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new bC(t,e,e,r,t,t,e,t,e,r,e,r)}}class mC{current;previous;cores;services;static Codec=_e.Class(mC,{current:Hr(hC.Codec),previous:Hr(hC.Codec),cores:OE(pC.Codec),services:_e.dictionary(uC,bC.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new mC(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 yC,AC;(AC=yC||(yC={}))[AC.DuplicateService=0]="DuplicateService",AC[AC.NoService=1]="NoService",AC[AC.PreimageExists=2]="PreimageExists";class IC extends _{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.toString())?.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.values()).map(e=>e.key),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=pt.new(),i=new Map,n=pt.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,tC.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 iC(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.toString(),rC.create({key:r,value:t}))}return new IC(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class vC extends _{static create(e){return new vC(e)}static partial(e,t){const r=vC.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=IC.copyFrom(t,i);r.set(s,n)}return vC.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,accumulationOutputLog:e.accumulationOutputLog,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.values()).map(e=>e.key),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 a;return Object.assign(this,n),a=this.updateServices(r),a.isError?a:(a=this.updatePreimages(s),a.isError?a:(a=this.updateStorage(i),a.isError?a:(this.removeServices(t),D.ok(O))))}removeServices(e){for(const t of e??[])w(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 D.error(yC.NoService,`Attempting to update storage of non-existing service: ${t}`);if(e===oC.Set){const{key:e,value:t}=r.storage;s.data.storage.set(e.toString(),rC.create({key:e,value:t}))}else if(e===oC.Remove){const{key:e}=r;w(s.data.storage.has(e.toString()),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(e.toString())}else E(e)}return D.ok(O)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return D.error(yC.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===nC.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return D.error(yC.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=ne(s.blob.length),n=new iC(s.hash,r,sC([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===nC.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===nC.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 E(s)}return D.ok(O)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===aC.Create){const{lookupHistory:e}=r;if(this.services.has(t))return D.error(yC.DuplicateService,`${t} already exists!`);this.services.set(t,new IC(t,{info:s,preimages:pt.new(),storage:new Map,lookupHistory:pt.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===aC.Update){const e=this.services.get(t);if(void 0===e)return D.error(yC.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else E(e)}return D.ok(O)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;accumulationOutputLog;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.accumulationOutputLog=e.accumulationOutputLog,this.services=e.services}static empty(e){return new vC({availabilityAssignment:RE(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Lr(Array.from({length:e.validatorsCount},()=>qE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(jE).asOpaque()})),e),nextValidatorData:Lr(Array.from({length:e.validatorsCount},()=>qE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(jE).asOpaque()})),e),currentValidatorData:Lr(Array.from({length:e.validatorsCount},()=>qE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(jE).asOpaque()})),e),previousValidatorData:Lr(Array.from({length:e.validatorsCount},()=>qE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(jE).asOpaque()})),e),disputesRecords:NE.create({goodSet:It.fromSortedArray(DE,[]),badSet:It.fromSortedArray(DE,[]),wonkySet:It.fromSortedArray(DE,[]),punishSet:It.fromSortedArray(DE,[])}),timeslot:Ur(0),entropy:yt.fill(()=>L.zero(Pe).asOpaque(),4),authPools:RE(Array.from({length:e.coresCount},()=>[]),e),authQueues:RE(Array.from({length:e.coresCount},()=>yt.fill(()=>L.zero(Pe).asOpaque(),80)),e),recentBlocks:GE.empty(),statistics:mC.create({current:Lr(Array.from({length:e.validatorsCount},()=>hC.empty()),e),previous:Lr(Array.from({length:e.validatorsCount},()=>hC.empty()),e),cores:RE(Array.from({length:e.coresCount},()=>pC.empty()),e),services:new Map}),accumulationQueue:Vr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Vr(Array.from({length:e.epochLength},()=>bt.new()),e),ticketsAccumulator:[],sealingKeySeries:JE.keys(Vr(Array.from({length:e.epochLength},()=>L.zero(Te).asOpaque()),e)),epochRoot:L.zero(De).asOpaque(),privilegedServices:PE.create({manager:Nr(0),authManager:RE(new Array(e.coresCount).fill(Nr(0)),e),validatorsManager:Nr(0),autoAccumulateServices:[]}),accumulationOutputLog:[],services:new Map})}}const wC=_e.object({storageKeys:_e.sequenceVarLen(_e.blob.convert(e=>e,e=>e)),preimages:_e.sequenceVarLen(_e.bytes(Pe).asOpaque()),lookupHistory:_e.sequenceVarLen(_e.object({hash:_e.bytes(Pe).asOpaque(),length:_e.u32}))});_e.dictionary(_e.u32.asOpaque(),wC,{sortKeys:(e,t)=>e-t});class SC extends _{report;dependencies;static Codec=_e.Class(SC,{report:ss.Codec,dependencies:xt(_e.bytes(Pe).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new SC(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var EC,CC,kC;function xC(e,t){const r=L.zero(Pe);let s=0;for(const i of de(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,Pe-i),s),r.asOpaque()}!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.Omega=14]="Omega",e[e.Xi=15]="Xi",e[e.Theta=16]="Theta",e[e.Delta=255]="Delta"}(EC||(EC={})),function(e){function t(e,t,r){const s=qe(P.blobFromParts(de(t),r.raw)).raw.subarray(0,28),i=L.zero(Pe);let n=0;for(const t of de(e))i.raw[n]=t,i.raw[n+1]=s[n/2],n+=2;const a=n/2;return i.raw.set(s.subarray(a),n),i.asOpaque()}e.index=function(e){const t=L.zero(Pe);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=L.zero(Pe);t.raw[0]=EC.Delta;let r=1;for(const s of de(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-1)),0),t.raw.set(r.raw.subarray(0,28),4),xC(e,t)}return t(e,ne(2**32-1),r)},e.servicePreimage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-2)),0),t.raw.set(r.raw.subarray(1,29),4),xC(e,t)}return t(e,ne(2**32-2),r)},e.serviceLookupHistory=function(e,r,s){if(v.isLessThan(h.V0_6_7)){const t=qe(r),i=L.zero(Pe);return i.raw.set(de(s),0),i.raw.set(t.raw.subarray(2,30),4),xC(e,i)}return t(e,s,r)},e.serviceNested=t}(CC||(CC={})),function(e){e.authPools={key:CC.index(EC.Alpha),Codec:OE(xt(_e.bytes(Pe).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:CC.index(EC.Phi),Codec:OE(_t(_e.bytes(Pe).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:CC.index(EC.Beta),Codec:GE.Codec,extract:e=>e.recentBlocks},e.safrole={key:CC.index(EC.Gamma),Codec:YE.Codec,extract:e=>YE.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:CC.index(EC.Psi),Codec:NE.Codec,extract:e=>e.disputesRecords},e.entropy={key:CC.index(EC.Eta),Codec:_t(_e.bytes(Pe).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:CC.index(EC.Iota),Codec:Hr(qE.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:CC.index(EC.Kappa),Codec:Hr(qE.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:CC.index(EC.Lambda),Codec:Hr(qE.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:CC.index(EC.Rho),Codec:OE(_e.optional(BE.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:CC.index(EC.Tau),Codec:_e.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:CC.index(EC.Chi),Codec:PE.Codec,extract:e=>e.privilegedServices},e.statistics={key:CC.index(EC.Pi),Codec:mC.Codec,extract:e=>e.statistics},e.accumulationQueue={key:CC.index(EC.Omega),Codec:Kr(ke(_e.sequenceVarLen(SC.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:CC.index(EC.Xi),Codec:Kr(_e.sequenceVarLen(_e.bytes(Pe).asOpaque()).convert(e=>Array.from(e),e=>bt.from(e))),extract:e=>e.recentlyAccumulated},e.accumulationOutputLog={key:CC.index(EC.Theta),Codec:_e.sequenceVarLen(xE.Codec),extract:e=>e.accumulationOutputLog},e.serviceData=e=>({key:CC.serviceInfo(e),Codec:eC.Codec}),e.serviceStorage=(e,t)=>({key:CC.serviceStorage(e,t),Codec:_C}),e.servicePreimages=(e,t)=>({key:CC.servicePreimage(e,t),Codec:_C}),e.serviceLookupHistory=(e,t,r)=>({key:CC.serviceLookupHistory(e,t,r),Codec:ke(_e.sequenceVarLen(_e.u32))})}(kC||(kC={}));const _C=Ce.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(L.fromBlob(t.raw,t.raw.length)),e=>P.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var BC;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(BC||(BC={}));const RC=P.empty();function OC(e,t){const r=new Uint8Array(4+t.length);return r.set(de(e)),r.set(t.raw,4),P.blobFrom(qe(r).raw)}class UC{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new UC(e,t,r)}static new(e,t,r=[]){return new UC(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}[M](){return this.backend}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(kC.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new TC(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 fe.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return fe.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(kC.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(kC.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(kC.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(kC.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(kC.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(kC.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(kC.timeslot,"timeslot")}get entropy(){return this.retrieve(kC.entropy,"entropy")}get authPools(){return this.retrieve(kC.authPools,"authPools")}get authQueues(){return this.retrieve(kC.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(kC.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(kC.statistics,"statistics")}get accumulationQueue(){return this.retrieve(kC.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(kC.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(kC.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(kC.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(kC.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(kC.privilegedServices,"privilegedServices")}get accumulationOutputLog(){return v.isGreaterOrEqual(h.V0_6_7)?this.retrieve(kC.accumulationOutputLog,"accumulationOutputLog"):[]}}class TC{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){if(v.isLessThan(h.V0_6_7)){const t=4,r=new Uint8Array(t+e.length);r.set(de(this.serviceId)),r.set(e.raw,t);const s=P.blobFrom(qe(r).raw);return this.retrieveOptional(kC.serviceStorage(this.serviceId,s))??null}return this.retrieveOptional(kC.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(kC.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(kC.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(kC.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:sC(r.map(Ur))}}class NC{hasher;nodes=pt.new();constructor(e){this.hasher=e}get(e){return NC.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()!==LS.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 DC extends NC{remove(e){return NC.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return NC.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class MC{nodes;root;static empty(e){return new MC(new DC(e))}static computeStateRoot(e,t){return MC.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new DC(e);for(const e of t)r=PC(r,s,e);return new MC(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=KS.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=PC(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?L.zero(Pe).asOpaque():this.nodes.hashNode(this.root)}toString(){return VC(this.root,this.nodes)}}function PC(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new LC;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==LS.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),a=HC(r,s.bitIndex),o=a?e.getRight():e.getLeft();s.branchingHistory.push([e,n,a]);const c=t.get(o);if(null===c){if(o.isEqualTo(L.zero(Pe)))return s;throw new Error(`Missing trie node '${o}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=o,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,a]=r;const o=n.getKey(),c=t.insert(s.node);if(o.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(a),[s.node,c];const l=[];let d=HC(i,e.bitIndex);for(;e.bitIndex<248;){d=HC(i,e.bitIndex);const t=HC(o,e.bitIndex);if(d!==t)break;l.push(t),e.bitIndex+=1}const u=L.zero(Pe).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!d&&(a=t.hashNode(n.node));let h=d?VS.fromSubNodes(a,c):VS.fromSubNodes(c,a),f=t.insert(h.node),g=l.pop();for(;void 0!==g;)h=g?VS.fromSubNodes(u,f):VS.fromSubNodes(f,u),f=t.insert(h.node),g=l.pop();return[h.node,f]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[a,o]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?VS.fromSubNodes(e.getLeft(),o):VS.fromSubNodes(o,e.getRight());o=t.insert(c.node),a=c.node,n=s.branchingHistory.pop()}return a}class LC{branchingHistory=[];bitIndex=0;leafToReplace}function HC(e,t){w(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function VC(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===LS.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),a=VC(t.get(s),t),o=VC(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(a)}\n\t-- ${i}: ${n(o)}\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 KC={hashConcat:(e,t=[])=>je([e,...t])};class QC{entries;static serializeInMemory(e,t){return new QC({full:!0,data:FC(e,t)})}static fromDictionaryUnsafe(e){return new QC({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new QC({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}[M](){return this.entries.data}getTrie(){if(null===this.trieCache){const e=MC.empty(KC);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===BC.Insert?this.entries.data.set(r,s):t===BC.Remove?this.entries.data.delete(r):E(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function FC(e,t){const r=pt.new();function s(s){r.set(s.key,Ae.encodeObject(s.Codec,s.extract(t),e))}s(kC.authPools),s(kC.authQueues),s(kC.recentBlocks),s(kC.safrole),s(kC.disputesRecords),s(kC.entropy),s(kC.designatedValidators),s(kC.currentValidators),s(kC.previousValidators),s(kC.availabilityAssignment),s(kC.timeslot),s(kC.privilegedServices),s(kC.statistics),s(kC.accumulationQueue),s(kC.recentlyAccumulated),v.isGreaterOrEqual(h.V0_6_7)&&s(kC.accumulationOutputLog);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=kC.serviceData(e);r.set(t,Ae.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=kC.servicePreimages(e,t.hash);r.set(s,Ae.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=kC.serviceStorage(e,t.key);r.set(s,Ae.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=kC.serviceLookupHistory(e,s.hash,s.length);r.set(t,Ae.encodeObject(i,s.slots.slice()))}}return r}const $C=(e,t,{typicalLength:r=32,compare:s=(e,r)=>{const s=t(e),i=t(r);return s<i?g.Less:s>i?g.Greater:g.Equal}}={})=>Ce.new(`Map<${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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=new Map,n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${t(a)}" >= "${t(n)}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)}),GC=_e.object({hash:_e.bytes(Pe).asOpaque(),length:_e.u32,slots:ke(_e.sequenceVarLen(_e.u32.asOpaque())).convert(R,sC)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new iC(e,t,r)),jC=_e.object({key:_e.bytes(Pe).asOpaque(),data:_e.sequenceVarLen(GC)}),qC=_e.sequenceVarLen(jC).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=pt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class zC extends IC{static Codec=_e.Class(zC,{serviceId:_e.u32.asOpaque(),data:_e.object({info:eC.Codec,preimages:Bt(tC.Codec,e=>e.hash),lookupHistory:qC,storage:$C(rC.Codec,e=>e.key.toString())})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new zC(e,t)}}var WC,JC,YC;_e.Class(vC,{authPools:kC.authPools.Codec,authQueues:kC.authQueues.Codec,recentBlocks:kC.recentBlocks.Codec,nextValidatorData:Hr(qE.Codec),epochRoot:_e.bytes(De).asOpaque(),sealingKeySeries:JE.Codec,ticketsAccumulator:ke(_e.sequenceVarLen(Ot.Codec)).convert(e=>e,mt),disputesRecords:kC.disputesRecords.Codec,entropy:kC.entropy.Codec,designatedValidatorData:kC.designatedValidators.Codec,currentValidatorData:kC.currentValidators.Codec,previousValidatorData:kC.previousValidators.Codec,availabilityAssignment:kC.availabilityAssignment.Codec,timeslot:kC.timeslot.Codec,privilegedServices:kC.privilegedServices.Codec,statistics:kC.statistics.Codec,accumulationQueue:kC.accumulationQueue.Codec,recentlyAccumulated:kC.recentlyAccumulated.Codec,accumulationOutputLog:kC.accumulationOutputLog.Codec,services:_e.dictionary(_e.u32.asOpaque(),zC.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(WC||(WC={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(JC||(JC={}));class XC{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return D.error(JC.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new HS(t.raw);if(e.getNodeType()===LS.Branch)return D.error(JC.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return D.ok(new XC(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=vt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:YC.EmbeddedValue,value:e.getValue()}:{kind:YC.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===YC.EmbeddedValue?t.value:t.kind===YC.DbKey?P.blobFrom(this.db.get(t.key)):void E(t)}getStateRoot(){return MC.computeStateRoot(KC,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(YC||(YC={}));class ZC{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=MC.empty(KC);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[BC.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===BC.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===BC.Remove?t.remove(i.asOpaque()):E(e);const i=P.blobFromParts(Array.from(t.nodes.leaves()).map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),a=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([a,n])}catch(e){return console.error(e),D.error(WC.Commit)}return D.ok(O)}async updateAndSetState(e,t,r){const s=MC.fromLeaves(KC,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[BC.Insert,r.key,Ae.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,kC.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,kC.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,kC.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return YE.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,kC.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,kC.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,kC.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,kC.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,kC.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,kC.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,kC.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,kC.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,kC.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,kC.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,kC.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,kC.recentlyAccumulated))}(e,t);const r=(t,r)=>Ae.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=kC.serviceData(s);if(yield[BC.Insert,e.key,t(e.Codec,r.account)],r.kind===aC.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=kC.serviceLookupHistory(s,e.hash,e.length);yield[BC.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 nC.Provide:{const{hash:e,blob:i}=r.preimage,n=kC.servicePreimages(s,e);if(yield[BC.Insert,n.key,i],null!==r.slot){const n=kC.serviceLookupHistory(s,e,ne(i.length));yield[BC.Insert,n.key,t(n.Codec,sC([r.slot]))]}break}case nC.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,a=kC.serviceLookupHistory(s,e,i);yield[BC.Insert,a.key,t(a.Codec,n)];break}case nC.Remove:{const{hash:e,length:t}=r,i=kC.servicePreimages(s,e);yield[BC.Remove,i.key,RC];const n=kC.serviceLookupHistory(s,e,t);yield[BC.Remove,n.key,RC];break}default:E(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case oC.Set:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.storage.key:OC(r,t.storage.key),s=kC.serviceStorage(r,e);yield[BC.Insert,s.key,t.storage.value];break}case oC.Remove:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.key:OC(r,t.key),s=kC.serviceStorage(r,e);yield[BC.Remove,s.key,RC];break}default:E(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=kC.serviceData(t);yield[BC.Remove,e.key,RC]}}(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=XC.fromLeavesBlob(P.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${P.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${N(s)}`);return UC.new(this.spec,s.ok)}}const ek=2**32,tk=Xs.new(void 0,"state-machine/port");class rk{port;listeners=new $n.EventEmitter;responseListeners=new $n.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw tk.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)%ek,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(sk(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){w("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 tk.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":w(-1!==this.responseListeners.eventNames().indexOf(sk(e.id))),this.responseListeners.emit(sk(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 sk(e){return`req:${e}`}const ik=Xs.new(void 0,"state-machine"),nk="channel";class ak{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 ik.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 ik.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),a=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!a)return this.port.respond(s.stateName,r,n.response);ik.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 ik.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new IE.MessageChannel,s=new rk(r.port2),i=e.currentState().stateName,[n,a]=s.prepareRequest(i,nk,r.port1);t.postMessage(n,[r.port1]);try{await a}catch(e){ik.error(JSON.stringify(e))}return new ak(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{w("request"===t.kind,"The initial message should be a request with channel."),w(t.name===nk),w(t.data instanceof IE.MessagePort);const s=new rk(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new ak(e,s)}}const ok=Symbol(),ck=Symbol();class lk{emitter=new $n.EventEmitter;emit(e){this.emitter.emit(ok,e)}on(e){return this.emitter.on(ok,e),this}off(e){return this.emitter.off(ok,e),this}once(e){return this.emitter.once(ok,e),this}onceDone(e){return this.emitter.once(ck,e),this}markDone(){this.emitter.emit(ck),this.emitter.removeAllListeners(ok),this.emitter.removeAllListeners(ck)}}class dk{name;state;allStates;stateListeners=new $n.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 w(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 uk=Xs.new(void 0,"state-machine/state");class hk{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){uk.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 fk extends hk{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class gk extends hk{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 pk extends hk{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 bk(e,t,r,s){const i=new IE.Worker(e),n=function(e,t,r){const s=new gk(t),i=new fk;return new dk(e,s,[s,r,i])}(`main->${r}`,r,s),a=await ak.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${a.currentState()}`),a}const mk=4294967295,yk=4294967296,Ak=4096,Ik=(w(!0,"incorrect minimal allocation shift"),7),vk=Ak>>Ik,wk=1048575,Sk=1048576,Ek=e=>S(e,e>=0&&e<=mk,`Incorrect memory index: ${e}!`),Ck=e=>S(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var kk,xk;(xk=kk||(kk={}))[xk.OK=255]="OK",xk[xk.HALT=0]="HALT",xk[xk.PANIC=1]="PANIC",xk[xk.FAULT=2]="FAULT",xk[xk.HOST=3]="HOST",xk[xk.OOG=4]="OOG";const _k=e=>S(e,e>=0&&e<=13,`Incorrect register index: ${e}!`);class Bk{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,w(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 w(104===e.length,"Invalid size of registers array."),new Bk(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]=Rk(t)}setI32(e,t){this.asSigned[e]=Rk(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 Rk(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}const Ok=e=>ne(e);var Uk,Tk;function Nk(...e){return e.map(_k)}!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(Uk||(Uk={}));class Dk{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return w(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 Dk(J.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"}(Tk||(Tk={}));class Mk{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 Pk{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 Lk{nibblesDecoder=new Pk;offsetDecoder=new Mk;code=new Uint8Array;mask=Dk.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 Tk.NO_ARGUMENTS:break;case Tk.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case Tk.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 Tk.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 Tk.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,a=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,a));const o=e+2+i,c=o+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(o,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Tk.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 Tk.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Tk.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const a=this.offsetDecoder.getSigned();t.nextPc=e+a;break}case Tk.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)),a=this.code.subarray(i,n);t.immediateDecoder.setBytes(a);break}case Tk.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Tk.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,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Tk.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(),a=e+3,o=a+n,c=this.code.subarray(a,o);t.firstImmediateDecoder.setBytes(c);const l=o,d=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,d);t.secondImmediateDecoder.setBytes(u);break}case Tk.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 Hk{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 Vk=Object.keys(Tk).length/2;var Kk;!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"}(Kk||(Kk={}));const Qk=Kk.MIN_U,Fk=(()=>{const e=new Array(Qk+1);return e[Kk.TRAP]=Tk.NO_ARGUMENTS,e[Kk.FALLTHROUGH]=Tk.NO_ARGUMENTS,e[Kk.ECALLI]=Tk.ONE_IMMEDIATE,e[Kk.LOAD_IMM_64]=Tk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[Kk.STORE_IMM_U8]=Tk.TWO_IMMEDIATES,e[Kk.STORE_IMM_U16]=Tk.TWO_IMMEDIATES,e[Kk.STORE_IMM_U32]=Tk.TWO_IMMEDIATES,e[Kk.STORE_IMM_U64]=Tk.TWO_IMMEDIATES,e[Kk.JUMP]=Tk.ONE_OFFSET,e[Kk.JUMP_IND]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_U8]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_I8]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_U16]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_I16]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_U32]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_I32]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.LOAD_U64]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.STORE_U8]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.STORE_U16]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.STORE_U32]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.STORE_U64]=Tk.ONE_REGISTER_ONE_IMMEDIATE,e[Kk.STORE_IMM_IND_U8]=Tk.ONE_REGISTER_TWO_IMMEDIATES,e[Kk.STORE_IMM_IND_U16]=Tk.ONE_REGISTER_TWO_IMMEDIATES,e[Kk.STORE_IMM_IND_U32]=Tk.ONE_REGISTER_TWO_IMMEDIATES,e[Kk.STORE_IMM_IND_U64]=Tk.ONE_REGISTER_TWO_IMMEDIATES,e[Kk.LOAD_IMM_JUMP]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_EQ_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_NE_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_LT_U_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_LE_U_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_GE_U_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_GT_U_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_LT_S_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_LE_S_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_GE_S_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.BRANCH_GT_S_IMM]=Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Kk.MOVE_REG]=Tk.TWO_REGISTERS,e[Kk.SBRK]=Tk.TWO_REGISTERS,e[Kk.COUNT_SET_BITS_64]=Tk.TWO_REGISTERS,e[Kk.COUNT_SET_BITS_32]=Tk.TWO_REGISTERS,e[Kk.LEADING_ZERO_BITS_64]=Tk.TWO_REGISTERS,e[Kk.LEADING_ZERO_BITS_32]=Tk.TWO_REGISTERS,e[Kk.TRAILING_ZERO_BITS_64]=Tk.TWO_REGISTERS,e[Kk.TRAILING_ZERO_BITS_32]=Tk.TWO_REGISTERS,e[Kk.SIGN_EXTEND_8]=Tk.TWO_REGISTERS,e[Kk.SIGN_EXTEND_16]=Tk.TWO_REGISTERS,e[Kk.ZERO_EXTEND_16]=Tk.TWO_REGISTERS,e[Kk.REVERSE_BYTES]=Tk.TWO_REGISTERS,e[Kk.STORE_IND_U8]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.STORE_IND_U16]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.STORE_IND_U32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.STORE_IND_U64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_U8]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_I8]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_U16]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_I16]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_U32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_I32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.LOAD_IND_U64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ADD_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ADD_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.AND_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.XOR_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.OR_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.MUL_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.MUL_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SET_LT_U_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SET_LT_S_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_L_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_R_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHAR_R_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.NEG_ADD_IMM_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_L_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_R_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHAR_R_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.NEG_ADD_IMM_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SET_GT_U_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SET_GT_S_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_L_IMM_ALT_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_R_IMM_ALT_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHAR_R_IMM_ALT_32]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_L_IMM_ALT_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHLO_R_IMM_ALT_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.SHAR_R_IMM_ALT_64]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.CMOV_IZ_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.CMOV_NZ_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ROT_R_64_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ROT_R_64_IMM_ALT]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ROT_R_32_IMM]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.ROT_R_32_IMM_ALT]=Tk.TWO_REGISTERS_ONE_IMMEDIATE,e[Kk.BRANCH_EQ]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.BRANCH_NE]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.BRANCH_LT_U]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.BRANCH_LT_S]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.BRANCH_GE_U]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.BRANCH_GE_S]=Tk.TWO_REGISTERS_ONE_OFFSET,e[Kk.LOAD_IMM_JUMP_IND]=Tk.TWO_REGISTERS_TWO_IMMEDIATES,e[Kk.ADD_32]=Tk.THREE_REGISTERS,e[Kk.ADD_64]=Tk.THREE_REGISTERS,e[Kk.SUB_32]=Tk.THREE_REGISTERS,e[Kk.SUB_64]=Tk.THREE_REGISTERS,e[Kk.AND]=Tk.THREE_REGISTERS,e[Kk.XOR]=Tk.THREE_REGISTERS,e[Kk.OR]=Tk.THREE_REGISTERS,e[Kk.MUL_32]=Tk.THREE_REGISTERS,e[Kk.MUL_64]=Tk.THREE_REGISTERS,e[Kk.MUL_UPPER_S_S]=Tk.THREE_REGISTERS,e[Kk.MUL_UPPER_U_U]=Tk.THREE_REGISTERS,e[Kk.MUL_UPPER_S_U]=Tk.THREE_REGISTERS,e[Kk.DIV_U_32]=Tk.THREE_REGISTERS,e[Kk.DIV_S_32]=Tk.THREE_REGISTERS,e[Kk.REM_U_32]=Tk.THREE_REGISTERS,e[Kk.REM_S_32]=Tk.THREE_REGISTERS,e[Kk.DIV_U_64]=Tk.THREE_REGISTERS,e[Kk.DIV_S_64]=Tk.THREE_REGISTERS,e[Kk.REM_U_64]=Tk.THREE_REGISTERS,e[Kk.REM_S_64]=Tk.THREE_REGISTERS,e[Kk.SET_LT_U]=Tk.THREE_REGISTERS,e[Kk.SET_LT_S]=Tk.THREE_REGISTERS,e[Kk.SHLO_L_32]=Tk.THREE_REGISTERS,e[Kk.SHLO_R_32]=Tk.THREE_REGISTERS,e[Kk.SHAR_R_32]=Tk.THREE_REGISTERS,e[Kk.SHLO_L_64]=Tk.THREE_REGISTERS,e[Kk.SHLO_R_64]=Tk.THREE_REGISTERS,e[Kk.SHAR_R_64]=Tk.THREE_REGISTERS,e[Kk.CMOV_IZ]=Tk.THREE_REGISTERS,e[Kk.CMOV_NZ]=Tk.THREE_REGISTERS,e[Kk.ROT_L_64]=Tk.THREE_REGISTERS,e[Kk.ROT_L_32]=Tk.THREE_REGISTERS,e[Kk.ROT_R_64]=Tk.THREE_REGISTERS,e[Kk.ROT_R_32]=Tk.THREE_REGISTERS,e[Kk.AND_INV]=Tk.THREE_REGISTERS,e[Kk.OR_INV]=Tk.THREE_REGISTERS,e[Kk.XNOR]=Tk.THREE_REGISTERS,e[Kk.MAX]=Tk.THREE_REGISTERS,e[Kk.MAX_U]=Tk.THREE_REGISTERS,e[Kk.MIN]=Tk.THREE_REGISTERS,e[Kk.MIN_U]=Tk.THREE_REGISTERS,e})(),$k=e=>ne(e),Gk=e=>oe(e),jk=e=>"number"==typeof e&&e<2**32?$k(e):Gk(e);function qk(e){return new zk(oe(e))}class zk{gas;constructor(e){this.gas=e}set(e){this.gas=oe(e)}get(){return jk(this.gas)}sub(e){const t=this.gas-oe(e);return t>=0n?(this.gas=oe(t),!1):(this.gas=oe(0n),!0)}}const Wk=[[Kk.TRAP,1],[Kk.FALLTHROUGH,1],[Kk.ECALLI,v.isSuite(f.JAMDUNA,h.V0_6_5)?0:1],[Kk.LOAD_IMM_64,1],[Kk.STORE_IMM_U8,1],[Kk.STORE_IMM_U16,1],[Kk.STORE_IMM_U32,1],[Kk.STORE_IMM_U64,1],[Kk.JUMP,1],[Kk.JUMP_IND,1],[Kk.LOAD_IMM,1],[Kk.LOAD_U8,1],[Kk.LOAD_I8,1],[Kk.LOAD_U16,1],[Kk.LOAD_I16,1],[Kk.LOAD_U32,1],[Kk.LOAD_I32,1],[Kk.LOAD_U64,1],[Kk.STORE_U8,1],[Kk.STORE_U16,1],[Kk.STORE_U32,1],[Kk.STORE_U64,1],[Kk.STORE_IMM_IND_U8,1],[Kk.STORE_IMM_IND_U16,1],[Kk.STORE_IMM_IND_U32,1],[Kk.STORE_IMM_IND_U64,1],[Kk.LOAD_IMM_JUMP,1],[Kk.BRANCH_EQ_IMM,1],[Kk.BRANCH_NE_IMM,1],[Kk.BRANCH_LT_U_IMM,1],[Kk.BRANCH_LE_U_IMM,1],[Kk.BRANCH_GE_U_IMM,1],[Kk.BRANCH_GT_U_IMM,1],[Kk.BRANCH_LT_S_IMM,1],[Kk.BRANCH_LE_S_IMM,1],[Kk.BRANCH_GE_S_IMM,1],[Kk.BRANCH_GT_S_IMM,1],[Kk.MOVE_REG,1],[Kk.SBRK,1],[Kk.COUNT_SET_BITS_64,1],[Kk.COUNT_SET_BITS_32,1],[Kk.LEADING_ZERO_BITS_64,1],[Kk.LEADING_ZERO_BITS_32,1],[Kk.TRAILING_ZERO_BITS_64,1],[Kk.TRAILING_ZERO_BITS_32,1],[Kk.SIGN_EXTEND_8,1],[Kk.SIGN_EXTEND_16,1],[Kk.ZERO_EXTEND_16,1],[Kk.REVERSE_BYTES,1],[Kk.STORE_IND_U8,1],[Kk.STORE_IND_U16,1],[Kk.STORE_IND_U32,1],[Kk.STORE_IND_U64,1],[Kk.LOAD_IND_U8,1],[Kk.LOAD_IND_I8,1],[Kk.LOAD_IND_U16,1],[Kk.LOAD_IND_I16,1],[Kk.LOAD_IND_U32,1],[Kk.LOAD_IND_I32,1],[Kk.LOAD_IND_U64,1],[Kk.ADD_IMM_32,1],[Kk.AND_IMM,1],[Kk.XOR_IMM,1],[Kk.OR_IMM,1],[Kk.MUL_IMM_32,1],[Kk.SET_LT_U_IMM,1],[Kk.SET_LT_S_IMM,1],[Kk.SHLO_L_IMM_32,1],[Kk.SHLO_R_IMM_32,1],[Kk.SHAR_R_IMM_32,1],[Kk.NEG_ADD_IMM_32,1],[Kk.SET_GT_U_IMM,1],[Kk.SET_GT_S_IMM,1],[Kk.SHLO_L_IMM_ALT_32,1],[Kk.SHLO_R_IMM_ALT_32,1],[Kk.SHAR_R_IMM_ALT_32,1],[Kk.CMOV_IZ_IMM,1],[Kk.CMOV_NZ_IMM,1],[Kk.ADD_IMM_64,1],[Kk.MUL_IMM_64,1],[Kk.SHLO_L_IMM_64,1],[Kk.SHLO_R_IMM_64,1],[Kk.SHAR_R_IMM_64,1],[Kk.NEG_ADD_IMM_64,1],[Kk.SHLO_L_IMM_ALT_64,1],[Kk.SHLO_R_IMM_ALT_64,1],[Kk.SHAR_R_IMM_ALT_64,1],[Kk.ROT_R_64_IMM,1],[Kk.ROT_R_64_IMM_ALT,1],[Kk.ROT_R_32_IMM,1],[Kk.ROT_R_32_IMM_ALT,1],[Kk.BRANCH_EQ,1],[Kk.BRANCH_NE,1],[Kk.BRANCH_LT_U,1],[Kk.BRANCH_LT_S,1],[Kk.BRANCH_GE_U,1],[Kk.BRANCH_GE_S,1],[Kk.LOAD_IMM_JUMP_IND,1],[Kk.ADD_32,1],[Kk.SUB_32,1],[Kk.MUL_32,1],[Kk.DIV_U_32,1],[Kk.DIV_S_32,1],[Kk.REM_U_32,1],[Kk.REM_S_32,1],[Kk.SHLO_L_32,1],[Kk.SHLO_R_32,1],[Kk.SHAR_R_32,1],[Kk.ADD_64,1],[Kk.SUB_64,1],[Kk.MUL_64,1],[Kk.DIV_U_64,1],[Kk.DIV_S_64,1],[Kk.REM_U_64,1],[Kk.REM_S_64,1],[Kk.SHLO_L_64,1],[Kk.SHLO_R_64,1],[Kk.SHAR_R_64,1],[Kk.AND,1],[Kk.XOR,1],[Kk.OR,1],[Kk.MUL_UPPER_S_S,1],[Kk.MUL_UPPER_U_U,1],[Kk.MUL_UPPER_S_U,1],[Kk.SET_LT_U,1],[Kk.SET_LT_S,1],[Kk.CMOV_IZ,1],[Kk.CMOV_NZ,1],[Kk.ROT_L_64,1],[Kk.ROT_L_32,1],[Kk.ROT_R_64,1],[Kk.ROT_R_32,1],[Kk.AND_INV,1],[Kk.OR_INV,1],[Kk.XNOR,1],[Kk.MAX,1],[Kk.MAX_U,1],[Kk.MIN,1],[Kk.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:$k(t)}])(t);return e[r]=s,e},{}),Jk=(()=>{const e=new Array(Qk+1);return e.fill(!1),e[Kk.TRAP]=!0,e[Kk.FALLTHROUGH]=!0,e[Kk.JUMP]=!0,e[Kk.JUMP_IND]=!0,e[Kk.LOAD_IMM_JUMP]=!0,e[Kk.LOAD_IMM_JUMP_IND]=!0,e[Kk.BRANCH_EQ]=!0,e[Kk.BRANCH_NE]=!0,e[Kk.BRANCH_GE_U]=!0,e[Kk.BRANCH_GE_S]=!0,e[Kk.BRANCH_LT_U]=!0,e[Kk.BRANCH_LT_S]=!0,e[Kk.BRANCH_EQ_IMM]=!0,e[Kk.BRANCH_NE_IMM]=!0,e[Kk.BRANCH_LT_U_IMM]=!0,e[Kk.BRANCH_LT_S_IMM]=!0,e[Kk.BRANCH_LE_U_IMM]=!0,e[Kk.BRANCH_LE_S_IMM]=!0,e[Kk.BRANCH_GE_U_IMM]=!0,e[Kk.BRANCH_GE_S_IMM]=!0,e[Kk.BRANCH_GT_U_IMM]=!0,e[Kk.BRANCH_GT_S_IMM]=!0,e})();class Yk{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&Jk[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 Xk=(()=>{const e=new Array(Qk+1);for(let t=0;t<Qk+1;t++){const r=Wk[t]?.gas;e[t]=r}return e})();class Zk{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const ex=e=>S(e,e>=0&&e<Ak,`Incorect page index: ${e}!`),tx=e=>S(e,e>=0&&e<=wk,`Incorrect page number: ${e}!`);function rx(e){return tx(e===wk?0:e+1)}function sx(e){return Ak*Math.ceil(e/Ak)}function ix(e){return tx(e>>>12)}function nx(e){return Ek(e>>>12<<12)}function ax(e){return Ek(e<<12>>>0)}class ox{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=ax(tx(e));return new ox(r,t)}static fromMemoryIndex(e,t=!1){const r=nx(Ek(e%yk));return new ox(r,t)}}class cx extends Error{constructor(){super("Out of bounds")}}Error,Error;class lx extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class dx extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class ux extends Error{constructor(){super("You are trying to access reserved memory!")}}class hx extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class fx extends Error{constructor(){super("Out of memory")}}class gx{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Ek((this.start+this.length)%yk),t>0&&(this.lastIndex=Ek((this.end-1+yk)%yk))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>yk)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new gx(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 px=gx.fromStartAndLength(Ek(0),65536);class bx{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=tx((this.start+this.length)%Sk)}static fromMemoryRange(e){const t=ix(e.start);if(e.isEmpty())return new bx(t,0);const r=ix(e.lastIndex??e.end),s=rx(r);if((t===s||t===r)&&e.length>Ak)return new bx(t,Sk);const i=t<s?s-t:Sk-t+s;return bx.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Sk)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new bx(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=rx(t)}while(t!==e)}}class mx{start;constructor(e){this.start=ax(e)}}class yx extends mx{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Ak)return D.error(ox.fromMemoryIndex(this.start+Ak));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){return D.error(ox.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Ax extends mx{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Ak,Math.max(r,vk));this.buffer=new ArrayBuffer(s,{maxByteLength:Ak}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Ak)return D.error(ox.fromMemoryIndex(this.start+Ak));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Ak){const r=Math.min(Ak,Math.max(vk,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),D.ok(O)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Ak){const r=Math.min(Ak,Math.max(vk,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Ix;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Ix||(Ix={}));class vx{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new vx(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=Ck(px.end),t=Ck(px.end),r=Ck(mk),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=Ck(px.end),this.virtualSbrkIndex=Ck(px.end),this.endHeapIndex=Ck(mk),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 D.ok(O);const r=this.getPages(e,t.length,Ix.WRITE);if(r.isError)return D.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=ex(i%Ak),a=Math.min(Ak-s,n),o=i-e,c=t.subarray(o,o+a);r.storeFrom(s,c),i+=a,n-=a}return D.ok(O)}getPages(e,t,r){if(0===t)return D.ok([]);const s=gx.fromStartAndLength(e,t),i=bx.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return D.error(ox.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return D.error(ox.fromPageNumber(e));if(r===Ix.WRITE&&!t.isWriteable())return D.error(ox.fromPageNumber(e,!0));n.push(t)}return D.ok(n)}loadInto(e,t){if(0===e.length)return D.ok(O);const r=this.getPages(t,e.length,Ix.READ);if(r.isError)return D.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=ex(i%Ak),a=Math.min(Ak-s,n),o=i-t,c=e.subarray(o);r.loadInto(c,s,a),i+=a,n-=a}return D.ok(O)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(mk<r+e||r+e>this.endHeapIndex)throw new fx;const s=Ck(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=Ck(sx(s)),n=ix(t),a=(i-t)/Ak,o=bx.fromStartAndLength(n,a);for(const e of o){const t=new Ax(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 wx{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new dx}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(px))throw new ux}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Ak===0,"start needs to be a multiple of page size (4096)"),w(t%Ak===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=gx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(bx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Ak,(e+1)*Ak),i=new yx(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Ak===0,"start needs to be a multiple of page size (4096)"),w(t%Ak===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=gx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(bx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Ak,(e+1)*Ak),i=new Ax(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Ak-e%Ak;w(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=gx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=ix(e),a=this.initialMemory.get(n);if(void 0===a)throw new hx;const o=ex(e-a.start);return a.setData(o,t),this}finalize(e,t){w(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=gx.fromStartAndLength(e,t-e),s=bx.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new lx;const i=vx.fromInitialMemory({memory:this.initialMemory,sbrkIndex:Ck(e),endHeapIndex:t});return this.isFinalized=!0,i}}class Sx{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 Kk.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Kk.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class Ex{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,a,o){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=a,this.bitRotationOps=o}dispatch(e,t){switch(e){case Kk.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Kk.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Kk.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class Cx{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 Kk.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Kk.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class kx{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case Kk.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case Kk.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Kk.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class xx{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case Kk.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Kk.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Kk.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Kk.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Kk.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Kk.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class _x{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===Kk.JUMP&&this.branchOps.jump(t.nextPc)}}class Bx{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case Kk.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case Kk.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Kk.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class Rx{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Kk.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Kk.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Kk.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Kk.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class Ox{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Kk.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Kk.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Kk.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Kk.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class Ux{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case Kk.TRAP:this.noArgsOps.trap();break;case Kk.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class Tx{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case Kk.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 Nx{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===Kk.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class Dx{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===Kk.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class Mx{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 Px=4294967295,Lx=-(2**31),Hx=32,Vx=64n;function Kx(e,t){return e>Px-t?Px-(Px-e+(Px-t))-1:e+t}function Qx(e,t){return(e+t)%2n**64n}function Fx(e,t){return t>e?Px-t+e+1:e-t}function $x(e,t){return(2n**64n+e-t)%2n**64n}function Gx(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 jx(e,t){return e*t%2n**64n}function qx(e){return e>=1n<<63n?e-(1n<<64n):e}function zx(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function Wx(e,t){return qx(0xffffffffffffffffn&e*t>>64n)}function Jx(e,t){w(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 Yx(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function Xx(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class Zx{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%Hx)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%Vx)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%Hx)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,Jx(this.regs.getU64(e),this.regs.getU64(t)%Vx))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%Hx)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%Vx)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%Hx)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%Vx)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%Hx)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,Jx(this.regs.getU64(e),t.getU64()%Vx))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%Hx)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%Vx)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%Hx)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%Vx)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%Hx)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,Jx(t.getU64(),this.regs.getU64(e)%Vx))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%Hx)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%Vx)}}class e_{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,Rk(Kx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,Qx(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,Rk(Kx(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,Qx(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,Rk(Gx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,jx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,zx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,Wx(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,qx(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,Rk(Gx(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,jx(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,Wx(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,zx(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,Rk(Fx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,$x(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,Rk(Fx(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,$x(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)===Lx?this.regs.setU64(r,Rk(this.regs.getLowerU32(e))):this.regs.setI64(r,Rk(~~(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,Rk(~~(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)===Lx?this.regs.setU64(r,0n):this.regs.setI64(r,Rk(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,Rk(this.regs.getLowerU32(e))):this.regs.setU64(r,Rk(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,Yx(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,Yx(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,Xx(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,Xx(this.regs.getU64(e),this.regs.getU64(t)))}}class t_{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 r_{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 s_,i_;(i_=s_||(s_={}))[i_.HALT=0]="HALT",i_[i_.PANIC=1]="PANIC",i_[i_.FAULT_ACCESS=2]="FAULT_ACCESS",i_[i_.FAULT=3]="FAULT",i_[i_.HOST=4]="HOST";class n_{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=s_.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 a_{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),Ek(e));i.isError?i.error.isAccessFault?this.instructionResult.status=s_.FAULT_ACCESS:(this.instructionResult.status=s_.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),Ek(e));i.isError?i.error.isAccessFault?this.instructionResult.status=s_.FAULT_ACCESS:(this.instructionResult.status=s_.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=Kx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class o_{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=Kx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=Kx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=Kx(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=Kx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=Kx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=Kx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=Kx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Ek(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=s_.FAULT_ACCESS:(this.instructionResult.status=s_.FAULT,this.instructionResult.exitParam=nx(r.error.address)))}}class c_{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=s_.PANIC}fallthrough(){}}class l_{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=s_.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=s_.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=s_.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=s_.PANIC}caluclateJumpAddress(e,t){return Kx(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class d_{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=s_.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class u_{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=s_.FAULT}}}class h_{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|Jx(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(Jx(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 f_{indices;constructor(e,t){w(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 f_(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const g_=Xs.new(void 0,"pvm-interpreter");var p_;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(p_||(p_={}));class b_{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 Dk(r),this.jumpTable=new f_(i,s)}decodeProgram(e){const t=fe.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,a=t.bytes(n).raw,o=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:o,jumpTableItemLength:s,jumpTable:a}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return D.ok(new b_(e))}catch(e){return g_.error(`Invalid program: ${e}`),D.error(p_.InvalidProgramError)}}}class m_{useSbrkGas;ignoreInstructionGas;registers=new Bk;code=new Uint8Array;mask=Dk.empty();pc=0;gas=qk(jk(0));initialGas=qk(jk(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new Zk;memory=new vx;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=kk.OK;argsDecodingResults=(()=>{const e=new Array(Vk);return e[Tk.NO_ARGUMENTS]={type:Tk.NO_ARGUMENTS,noOfBytesToSkip:1},e[Tk.ONE_IMMEDIATE]={type:Tk.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new Mk},e[Tk.TWO_REGISTERS]={type:Tk.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[Tk.THREE_REGISTERS]={type:Tk.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Mk,nextPc:0},e[Tk.TWO_REGISTERS_ONE_OFFSET]={type:Tk.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[Tk.TWO_REGISTERS_ONE_IMMEDIATE]={type:Tk.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new Mk},e[Tk.ONE_REGISTER_ONE_IMMEDIATE]={type:Tk.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Mk},e[Tk.ONE_REGISTER_TWO_IMMEDIATES]={type:Tk.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new Mk,secondImmediateDecoder:new Mk},e[Tk.ONE_OFFSET]={type:Tk.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[Tk.TWO_IMMEDIATES]={type:Tk.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Mk,secondImmediateDecoder:new Mk},e[Tk.TWO_REGISTERS_TWO_IMMEDIATES]={type:Tk.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Mk,secondImmediateDecoder:new Mk,firstRegisterIndex:0,secondRegisterIndex:0},e[Tk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:Tk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new Hk},e})();basicBlocks;jumpTable=f_.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new Lk,this.basicBlocks=new Yk;const r=new e_(this.registers),s=new Zx(this.registers),i=new Mx(this.registers),n=new t_(this.registers),a=new r_(this.registers),o=new n_(this.registers,this.instructionResult,this.basicBlocks),c=new a_(this.registers,this.memory,this.instructionResult),l=new o_(this.registers,this.memory,this.instructionResult),d=new c_(this.instructionResult),u=new l_(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),h=new d_(this.instructionResult),f=new u_(this.registers,this.memory,this.instructionResult),g=new h_(this.registers);this.threeRegsDispatcher=new Sx(r,s,i,n,a,g),this.twoRegsOneImmDispatcher=new Ex(r,s,i,n,a,l,c,g),this.twoRegsDispatcher=new Cx(a,f,i,g),this.oneRegOneImmOneOffsetDispatcher=new kx(o,c),this.twoRegsOneOffsetDispatcher=new xx(o),this.oneOffsetDispatcher=new _x(o),this.oneRegOneImmDispatcher=new Bx(c,l,u),this.twoImmsDispatcher=new Ox(l),this.oneRegTwoImmsDispatcher=new Rx(l),this.noArgsDispatcher=new Ux(d),this.twoRegsTwoImmsDispatcher=new Tx(c,u),this.oneImmDispatcher=new Nx(h),this.oneRegOneExtImmDispatcher=new Dx(c)}reset(e,t,r,s,i){const n=new b_(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=qk(r),this.initialGas=qk(r),this.status=kk.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([Kk[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===kk.OK;);}nextStep(){this.status===kk.HOST&&(this.status=kk.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??Kk.TRAP,t=void 0!==Kk[e],r=Xk[e]??Xk[Kk.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=kk.OOG,this.status;const s=Fk[e]??Tk.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 Tk.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case Tk.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case Tk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case Tk.TWO_REGISTERS:if(this.useSbrkGas&&e===Kk.SBRK){const e=e=>sx(e)/Ak*16;if(this.gas.sub(jk(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=kk.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case Tk.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case Tk.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case Tk.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case Tk.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case Tk.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case Tk.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case Tk.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case Tk.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case Tk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=s_.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==s_.FAULT&&this.instructionResult.status!==s_.FAULT_ACCESS||this.gas.sub(Xk[Kk.TRAP]),this.instructionResult.status){case s_.FAULT:this.status=kk.FAULT;break;case s_.HALT:this.status=kk.HALT;break;case s_.PANIC:case s_.FAULT_ACCESS:this.status=kk.PANIC;break;case s_.HOST:this.status=kk.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=Gk(this.initialGas.get())-Gk(this.gas.get());return e<0?this.initialGas.get():Gk(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?ne(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(tx(e))}}class y_{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?D.ok(O):e+oe(t.length)>yk?D.error(new cx):this.memory.storeFrom(Ek(Number(e)),t)}loadInto(e,t){return 0===e.length?D.ok(O):t+oe(e.length)>yk?D.error(new cx):this.memory.loadInto(e,Ek(Number(t)))}getMemory(){return this.memory}}class A_{registers;constructor(e){this.registers=e}get(e){return oe(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class I_{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,w(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 I_(e,t,null)}static fromMemorySlice(e,t){return new I_(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class v_{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===kk.OOG)return I_.fromStatus(r,e);if(e===kk.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),a=new Uint8Array(n),o=Ek(i);return e.loadInto(a,o).isError?I_.fromMemorySlice(r,new Uint8Array):I_.fromMemorySlice(r,a)}return I_.fromStatus(r,kk.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==kk.HOST)return this.getReturnValue(t,e);w(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 A_(e.getRegisters()),n=new y_(e.getMemory()),a=Ok(r),o=this.hostCalls.get(a),c=s.get(),l="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(l))return this.hostCalls.traceHostCall("OOG",a,o,i,s.get()),I_.fromStatus(e.getGasConsumed(),kk.OOG);this.hostCalls.traceHostCall("Invoking",a,o,i,c);const d=await o.execute(s,i,n);if(this.hostCalls.traceHostCall(void 0===d?"Result":`Status(${d})`,a,o,i,s.get()),d===Uk.Halt)return t=kk.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 w_{instances=[];waitingQueue=[];constructor(e){const t=v.isGreaterOrEqual(h.V0_6_7)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.W3F_DAVXY,h.V0_6_6);for(let r=0;r<e;r++)this.instances.push(new m_({useSbrkGas:!1,ignoreInstructionGas:!t}))}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 S_={NONE:oe(0xffffffffffffffffn),WHAT:oe(0xfffffffffffffffen),OOB:oe(0xfffffffffffffffdn),WHO:oe(0xfffffffffffffffcn),FULL:oe(0xfffffffffffffffbn),CORE:oe(0xfffffffffffffffan),CASH:oe(0xfffffffffffffff9n),LOW:oe(0xfffffffffffffff8n),HUH:oe(0xfffffffffffffff7n),OK:oe(0n)},E_=ne(2**32-1),C_=oe(E_),k_=Nr(2**32-1);function x_(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:__(s)}function __(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?Nr(t):null}function B_(e){return e>C_?E_:ne(Number(e))}const R_=Xs.new(void 0,"host-calls");class O_{hostCalls=new Map;missing=new U_;constructor(...e){for(const t of e)w(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){return this.hostCalls.get(e)??this.missing}traceHostCall(e,t,r,s,i){const{currentServiceId:n}=r,a=t!==r.index?` (${t})`:"",o=`${r.constructor.name}:${r.index}`,c=r.tracedRegisters.map(e=>[e.toString().padStart(2,"0"),s.get(e)]).filter(e=>0n!==e[1]).map(([e,t])=>`r${e}=${t} (0x${t.toString(16)})`).join(", ");R_.trace(`[${n}] ${e} ${o}${a}. Gas: ${i}. Regs: ${c}.`)}}class U_{index=Ok(2**32-1);gasCost=$k(10);currentServiceId=k_;tracedRegisters=Nk(7);execute(e,t,r){return t.set(7,S_.WHAT),Promise.resolve(void 0)}}const T_=4096,N_=65536,D_=2**24,M_=4278059008,P_=4278124544;function L_(e){return T_*Math.ceil(e/T_)}class H_ extends _{start;end;data;static from({start:e,end:t,data:r}){return new H_(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class V_ extends _{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class K_ extends _{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function Q_(e,t,r=null){return new H_(e,t,r)}class F_{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?$_(e):{code:e},{code:n,memory:a,registers:o}=function(e,t){const r=fe.fromBlob(e),s=r.u24(),i=r.u24(),n=S(t.length,t.length<=D_,"Incorrect arguments length"),a=S(s,s<=D_,"Incorrect readonly segment length"),o=S(i,i<=D_,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),d=r.bytes(a).raw,u=r.bytes(o).raw,h=r.u32(),f=r.bytes(h).raw;r.finish();const g=N_+L_(a),p=131072+(b=a,N_*Math.ceil(b/N_));var b;const m=p+L_(o),y=p+L_(o)+c*T_,A=M_-L_(l),I=M_,v=P_,w=v+L_(n),E=w+L_(n);function C(e){return!1!==e}const k=[a>0&&Q_(65536,g,d),n>0&&Q_(v,w,t),w<E&&Q_(w,E)].filter(C),x=[o>0&&Q_(p,m,u),m<y&&Q_(m,y),A<I&&Q_(A,I)].filter(C);return new K_(f,new V_(k,x,y,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(M_),t[7]=BigInt(P_),t[8]=BigInt(e),t}(t.length))}(s,t),c=new Bk;c.copyFrom(o);const l=new wx;for(const{start:e,end:t,data:r}of a.readable){const s=Ek(e),i=Ek(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of a.writeable){const s=Ek(e),i=Ek(t);l.setWriteablePages(s,i,r??new Uint8Array)}const d=Ek(a.sbrkIndex),u=Ck(a.heapEnd),h=l.finalize(d,u);return new F_(n,c,h,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?$_(e):{code:e},i=new Bk,n=new vx;return new F_(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function $_(e){const t=fe.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var G_,j_,q_;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(G_||(G_={}));class z_{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return gt(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return gt(this.keccakHasher,[e,t,r])}header(e){return new He(qe(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=qe(e.report.encoded(),this.allocator).asOpaque();return P.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=Ae.encodeObject(_e.sequenceVarLen(_C),t,this.context),s=qe(e.tickets.encoded(),this.allocator).asOpaque(),i=qe(e.preimages.encoded(),this.allocator).asOpaque(),n=qe(r,this.allocator).asOpaque(),a=qe(e.assurances.encoded(),this.allocator).asOpaque(),o=qe(e.disputes.encoded(),this.allocator).asOpaque(),c=P.blobFromParts([s.raw,i.raw,n.raw,a.raw,o.raw]);return new Ve(qe(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Wr.Codec,e)}encode(e,t){const r=Ae.encodeObject(e,t,this.context);return new Ve(qe(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(j_||(j_={}));class W_{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 D.error(j_.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=qe(i).asOpaque(),a=this.state.getService(t);if(null===a)return D.error(j_.AccountNotFound);const o=a.hasPreimage(n),c=a.getLookupHistory(n,ne(i.length));if(o||null===c||!iC.isRequested(c))return D.error(j_.PreimageUnneeded);s.push(cC.provide({serviceId:t,preimage:tC.create({hash:n,blob:i}),slot:r}))}return D.ok({preimages:s})}}class J_{spec;importer;toImport=At.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?g.Greater:r>0?g.Less:g.Equal});queuedBlocks=bt.new();lastEpoch=Pr(2**32-1);constructor(e,t){this.spec=e,this.importer=t}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))}static getBlockDetails(e){let t,r;try{t=e.header.encoded(),r=e.header.view().timeSlotIndex.materialize()}catch{return D.error("invalid")}const s=qe(t).asOpaque();return D.ok(new He(s,{block:e,timeSlot:r}))}push(e){const t=e.hash;if(this.queuedBlocks.has(t))return D.error("already queued");const{timeSlot:r,block:s}=e.data,i={headerHash:t,timeSlot:r,block:s,seal:this.isCurrentEpoch(r)?this.importer.preverifySeal(r,s):Promise.resolve(null)};return this.toImport.insert(i),this.queuedBlocks.insert(t),D.ok(O)}shift(){const e=this.toImport.pop();if(void 0!==e){this.queuedBlocks.delete(e.headerHash);const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=Pr(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"}(q_||(q_={}));const Y_=L.zero(Pe).asOpaque();class X_{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 D.error(q_.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(Y_)){const e=this.blocks.getHeader(s);if(null===e)return D.error(q_.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return D.error(q_.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 D.error(q_.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const a=t.priorStateRoot.materialize(),o=this.blocks.getPostStateRoot(s);return null===o?D.error(q_.StateRootNotFound,`Posterior state root ${s.toString()} not found`):a.isEqualTo(o)?D.ok(r.hash):D.error(q_.InvalidStateRoot,`Invalid prior state root: ${a.toString()}, expected ${o.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var Z_;function eB(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"}(Z_||(Z_={}));const tB=P.blobFromString("jam_valid").raw,rB=P.blobFromString("jam_invalid").raw,sB=P.blobFromString("jam_guarantee").raw;function iB({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:P.blobFromParts(sB,r.raw)}}function nB({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?tB:rB;return{key:s,signature:r,message:P.blobFromParts(i,e.raw)}}function aB(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?tB:rB;return{key:r,signature:i,message:P.blobFromParts(n,t.raw)}}class oB{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!eB(e.culprits,"key"))return D.error(Z_.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(Z_.OffenderAlreadyReported);if(!s.has(i))return D.error(Z_.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(a))return D.error(Z_.CulpritsVerdictNotBad);const o=r.culprits[n];if(!o?.isValid)return D.error(Z_.BadSignature)}return D.ok(null)}verifyFaults(e,t,r,s){if(!eB(e.faults,"key"))return D.error(Z_.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a,wasConsideredValid:o}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(Z_.OffenderAlreadyReported);if(!s.has(i))return D.error(Z_.BadAuditorKey);if(o){const e=t.toAddToGoodSet.findExact(a),r=t.toAddToBadSet.findExact(a);if(void 0!==e||void 0===r)return D.error(Z_.FaultVerdictWrong)}if(!r.faults[n].isValid)return D.error(Z_.BadSignature)}return D.ok(null)}verifyVerdicts(e,t){if(!eB(e.verdicts,"workReportHash"))return D.error(Z_.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 D.error(Z_.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 D.error(Z_.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 D.error(Z_.BadValidatorIndex);if(!t.judgements[s].isValid)return D.error(Z_.BadSignature);s+=1}}return D.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 D.error(Z_.AlreadyJudged)}return D.ok(null)}calculateVotesForWorkReports(e){const t=pt.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 D.error(Z_.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 D.error(Z_.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return D.error(Z_.BadVoteSplit);return D.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:It.fromArrayUnique(DE,t),toAddToBadSet:It.fromArrayUnique(DE,r),toAddToWonkySet:It.fromArrayUnique(DE,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 RE(t,this.chainSpec)}getOffenders(e){const t=bt.new();for(const{key:r}of e.culprits)t.insert(r);for(const{key:r}of e.faults)t.insert(r);return t}getUpdatedDisputesRecords(e,t){const r=At.fromArray(DE,Array.from(t));return NE.create({goodSet:It.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:It.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:It.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:It.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 D.error(Z_.BadValidatorIndex);const i=s.ed25519;t.judgements.push(aB(r,n,i))}}return t.culprits=e.culprits.map(iB),t.faults=e.faults.map(nB),D.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 bt.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return D.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 wr(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,a=this.getValidatorKeys(),o=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,a),this.verifyFaults(e,i,n,a),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(o?.isError)return D.error(o.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),d=this.getClearedCoreAssignment(s);return D.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:d}})}}const cB=P.blobFromString("jam_entropy").raw,lB=P.blobFromString("jam_fallback_seal").raw,dB=P.blobFromString("jam_ticket_seal").raw;var uB;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(uB||(uB={}));const hB=async function(e,t,r,s,i,n){const a=P.blobFromParts(t.map(e=>e.raw)).raw,o=await e.verifySeal(a,r,s.raw,i.raw,n.raw);return o[0]===uB.Error?D.error(null):D.ok(L.fromBlob(o.subarray(1),Pe).asOpaque())},fB=async function(e,t,r,s){const i=s.length+dB.length+1,n=P.blobFromParts(r.map(e=>P.blobFromParts([e.signature.raw,dB,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,a=P.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(a,n,i);return Array.from(P.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===uB.Ok,entropyHash:L.fromBlob(e.raw.subarray(1,33),Pe).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:L.zero(Pe).asOpaque()}));throw e}},gB=async function(e,t){const r=P.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===uB.Error?D.error(null):D.ok(L.fromBlob(s.subarray(1),De).asOpaque())};class pB{runInternal;state;static new(e,t){return new pB(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===IE.parentPort)throw new Error("This method is meant to be run inside a worker thread!");IE.parentPort.once("close",()=>{process.exit(0)}),IE.parentPort.once("message",e=>{this.listenTo(e),IE.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=D.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=D.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class bB{workers;maxWorkers;workerPath;static async initialize(e,t){w(t.maxWorkers>0,"Max workers has to be positive."),w(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 mB(e));return new bB(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 mB(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 mB(e){const{port1:t,port2:r}=new MessageChannel,s=new IE.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new yB(s,r)}class yB{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 AB;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(AB||(AB={}));class IB{data;constructor(e){this.data=e}getTransferList(){return[]}}class vB{params;constructor(e){this.params=e}getTransferList(){return[]}}const wB=pB.new(e=>{const t=e.params,r=t.method;return r===AB.RingCommitment?Promise.resolve(new IB(Ue.ring_commitment(t.keys))):r===AB.BatchVerifyTickets?Promise.resolve(new IB(Ue.batch_verify_tickets(t.keys,t.ticketsData,t.contextLength))):r===AB.VerifySeal?Promise.resolve(new IB(Ue.verify_seal(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void E(r)},null);class SB{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=dE().cpus().length;return new SB(e?wB:await bB.initialize(new URL(a(884),a.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new vB({method:AB.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new vB({method:AB.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new vB({method:AB.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const EB=(e,t)=>W(e.id,t.id);var CB,kB,xB,_B,BB,RB,OB,UB,TB;!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"}(CB||(CB={}));class NB{chainSpec;state;bandersnatch;constructor(e,t,r=SB.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=je([r.raw,t]).asOpaque();return this.isEpochChanged(e)?yt.new([i,r,s[0],s[1]],4):yt.new([i,...s],4)}async getValidatorKeys(e,t){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return D.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?qE.create({bandersnatch:L.zero(Te).asOpaque(),ed25519:L.zero(mr).asOpaque(),bls:L.zero(Me).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await gB(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?D.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):D.error(CB.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]),Vr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=ne(0);n<r;n++){const r=de(n),a=je([e.raw,r]).raw,o=fe.fromBlob(a).u32()%i;s.push(t[o].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?JE.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:JE.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return ls.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>cs.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 D.error(CB.DuplicateTicket);if(t.isGreater())return D.error(CB.BadTicketOrder)}return D.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await fB(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 D.error(CB.BadTicketProof);const a=this.verifyTickets(n);if(a.isError)return D.error(a.error);if(this.isEpochChanged(e))return D.ok(n);const o=It.fromSortedArray(EB,this.state.ticketsAccumulator),c=It.fromSortedArray(EB,n),l=It.fromTwoSortedCollections(o,c);return o.length+c.length!==l.length?D.error(CB.DuplicateTicket):D.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 D.error(CB.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return D.error(CB.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return D.error(CB.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot,e.punishSet);if(t.isError)return D.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,a=this.getEntropy(e.slot,e.entropy),o=this.getSlotKeySequence(e.slot,s,a[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,a[2]);if(c.isError)return D.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:a,sealingKeySeries:o,ticketsAccumulator:c.ok},d={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return D.ok(d)}}!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"}(kB||(kB={}));class DB{bandersnatch;constructor(e=SB.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=P.blobFromParts(cB,r.ok.raw),i=await hB(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,P.blobFromNumbers([]));return i.isError?D.error(kB.IncorrectEntropySource):D.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return D.error(kB.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),a=t.sealingKeySeries,o=t.currentEntropy;return a.kind===zE.Tickets?await this.verifySealWithTicket(a.tickets,n,o,r,s,e):await this.verifySealWithKeys(a.keys,i,n,o,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const a=t%e.length,{id:o,attempt:c}=e[a],l=P.blobFromParts(dB,r.raw,new Uint8Array([c])),d=await hB(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,ds(n));return d.isError?D.error(kB.IncorrectSeal):o.isEqualTo(d.ok)?D.ok(d.ok):D.error(kB.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,a){if(!e[r%e.length].isEqualTo(t.bandersnatch))return D.error(kB.InvalidValidator);const o=P.blobFromParts(lB,s.raw),c=await hB(await this.bandersnatch,i.map(e=>e.bandersnatch),n,a.seal.materialize(),o,ds(a));return c.isError?D.error(kB.IncorrectSeal):D.ok(c.ok)}}function MB(e){if(e.length===xB.Requested)return{status:xB.Requested};if(e.length===xB.Available)return{status:xB.Available,data:[e[0]]};if(e.length===xB.Unavailable)return{status:xB.Unavailable,data:[e[0],e[1]]};if(e.length===xB.Reavailable)return{status:xB.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"}(xB||(xB={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(_B||(_B={})),function(e){e[e.NotFound=0]="NotFound",e[e.NotExpired=1]="NotExpired",e[e.StorageUtilisationError=2]="StorageUtilisationError"}(BB||(BB={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(RB||(RB={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(OB||(OB={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(UB||(UB={})),function(e){e[e.InsufficientFunds=0]="InsufficientFunds",e[e.UnprivilegedService=1]="UnprivilegedService"}(TB||(TB={}));class PB{source;destination;amount;memo;gas;static Codec=_e.Class(PB,{source:_e.u32.asOpaque(),destination:_e.u32.asOpaque(),amount:_e.u64,memo:_e.bytes(128),gas:_e.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 PB(e,t,r,s,i)}}const LB="insufficient funds";class HB{services;transfers;yieldedRoots;authorizationQueues=new Map;validatorsData=null;privilegedServices=null;constructor(e,t,r=new Map){this.services=e,this.transfers=t,this.yieldedRoots=r}static empty(){return new HB({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new HB({...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 HB(t,r,new Map(e.yieldedRoots));for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return null!==e.validatorsData&&(s.validatorsData=[...e.validatorsData]),null!==e.privilegedServices&&(s.privilegedServices=PE.create({...e.privilegedServices,authManager:[...e.privilegedServices.authManager]})),s}}class VB{state;stateUpdate;constructor(e,t){this.state=e,this.stateUpdate=void 0===t?HB.empty():HB.copyFrom(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===nC.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:ne(Number(e))}(s);if(null===i||null===e)return null;const n=e.getLookupHistory(r,i);return null===n?null:new iC(r,i,n)};if(void 0===i)return n();const{action:a}=i;switch(a.kind){case nC.Provide:return new iC(r,i.length,sC([e]));case nC.Remove:{const t=n();return null===t?null:new iC(r,t.length,sC([...t.slots,e]))}case nC.UpdateOrAdd:return a.item}E(a)}updateStorage(e,t,r){const s=null===r?dC.remove({serviceId:e,key:t}):dC.set({serviceId:e,storage:rC.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){w(t>=0,`storageUtilisationCount has to be a positive number, got: ${t}`),w(r>=0,`storageUtilisationBytes has to be a positive number, got: ${r}`);const i=!ae(t),n=!ce(r);if(i||n)return D.error(LB);const a=eC.calculateThresholdBalance(t,r,s.gratisStorage);return s.balance<a?D.error(LB):(this.updateServiceInfo(e,eC.create({...s,storageUtilisationBytes:r,storageUtilisationCount:t})),D.ok(O))}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!==aC.Create?this.stateUpdate.services.servicesUpdates.splice(r,s,lC.update({serviceId:e,serviceInfo:t})):this.stateUpdate.services.servicesUpdates.splice(r,s,lC.create({serviceId:e,serviceInfo:t,lookupHistory:i.action.lookupHistory}))}getPrivilegedServices(){return null!==this.stateUpdate.privilegedServices?this.stateUpdate.privilegedServices:this.state.privilegedServices}}const KB=oe(81),QB=v.isGreaterOrEqual(h.V0_6_7)?oe(34):oe(32),FB=Xs.new(void 0,"accumulate-externalities");class $B{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:MB(s.slots);if(i?.status!==xB.Unavailable)return[!1,"wrong status"];const n=this.currentTimeslot,a=i.data[1]<n-this.chainSpec.preimageExpungePeriod;return[a,a?"":"not expired"]}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=Nr((t-256+1+r)%r+256)}}getManager(){return this.updatedState.getPrivilegedServices().manager}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:MB(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===xB.Requested)return D.error(_B.AlreadyRequested);if(e===xB.Available||e===xB.Reavailable)return D.error(_B.AlreadyAvailable);w(e===xB.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,a=t-BigInt(r?.length??0),o=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(a)+(i?0n:KB),l=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,o,c,s);if(l.isError)return D.error(_B.InsufficientFunds,l.details);const d=B_(t);return null===r?this.updatedState.updatePreimage(cC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new iC(e,d,sC([]))})):this.updatedState.updatePreimage(cC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new iC(e,d,sC([...r.slots,this.currentTimeslot]))})),D.ok(O)}forgetPreimage(e,t){const r=this.currentServiceId,s=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null===s)return D.error(BB.NotFound);const i=MB(s.slots),n=()=>{const e=this.getCurrentServiceInfo(),r=e.storageUtilisationCount-2,s=e.storageUtilisationBytes-t-KB;return this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,r,s,e)};if(i.status===xB.Requested)return n().isError?D.error(BB.StorageUtilisationError):(this.updatedState.updatePreimage(cC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O));const a=this.currentTimeslot;return i.status===xB.Unavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?n().isError?D.error(BB.StorageUtilisationError):(this.updatedState.updatePreimage(cC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O)):D.error(BB.NotExpired):i.status===xB.Available?(this.updatedState.updatePreimage(cC.updateOrAdd({serviceId:r,lookupHistory:new iC(s.hash,s.length,sC([i.data[0],a]))})),D.ok(O)):i.status===xB.Reavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(cC.updateOrAdd({serviceId:r,lookupHistory:new iC(s.hash,s.length,sC([i.data[2],a]))})),D.ok(O)):D.error(BB.NotExpired):void E(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return D.error(RB.DestinationNotFound);if(r<n.onTransferMinGas)return D.error(RB.GasTooLow);const a=i.balance-t;return a<eC.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes,i.gratisStorage)?D.error(RB.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(PB.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,eC.create({...i,balance:oe(a)})),D.ok(O))}newService(e,t,r,s,i){const n=this.nextNewServiceId,a=ne(2),o=le(KB,t),c=B_(t);if(i!==oe(0)&&this.currentServiceId!==this.getManager())return D.error(TB.UnprivilegedService);const l=eC.calculateThresholdBalance(a,o.value,i),d=this.getCurrentServiceInfo(),u=eC.calculateThresholdBalance(d.storageUtilisationCount,d.storageUtilisationBytes,d.gratisStorage),h=d.balance-l;return h<u||o.overflow?D.error(TB.InsufficientFunds):(this.updatedState.stateUpdate.services.servicesUpdates.push(lC.create({serviceId:n,serviceInfo:eC.create({codeHash:e,balance:l,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:a,gratisStorage:i,created:this.currentTimeslot,lastAccumulation:Ur(0),parentService:this.currentServiceId}),lookupHistory:new iC(e.asOpaque(),c,sC([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,eC.create({...d,balance:oe(h)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return Nr(256+(e-256+42+t)%t)}(n)),D.ok(n))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updateServiceInfo(this.currentServiceId,eC.create({...s,codeHash:e,accumulateMinGas:Dr(t),onTransferMinGas:Dr(r)}))}updateValidatorsData(e){const t=this.updatedState.getPrivilegedServices().validatorsManager;t===this.currentServiceId?this.updatedState.stateUpdate.validatorsData=e:FB.trace(`Current service id (${this.currentServiceId}) is not a validator manager (${t}) and cannot update validators. Ignoring.`)}checkpoint(){this.checkpointedState=HB.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t){const r=this.updatedState.getPrivilegedServices().authManager[e];r===this.currentServiceId?this.updatedState.stateUpdate.authorizationQueues.set(e,t):FB.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=PE.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>ME.create({service:e,gasLimit:t}))}):FB.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 D.error(UB.ServiceNotFound);const r=qe(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,oe(t.length));return null!==s&&iC.isRequested(s)?this.updatedState.hasPreimage(e,r)?D.error(UB.AlreadyProvided):(this.updatedState.updatePreimage(cC.provide({serviceId:e,preimage:tC.create({hash:r,blob:t}),slot:this.currentTimeslot})),D.ok(O)):D.error(UB.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return D.error(OB.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=L.zero(Pe).asOpaque();if(function(e,t){w(t.length>=4,"Not enough space in the destination."),t.set(de(e))}(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return D.error(OB.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return D.error(OB.InvalidPreimage,"Too many storage items");const n=oe(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,KB)-KB),[a,o]=this.isPreviousCodeExpired(e,t,n);if(!a)return D.error(OB.InvalidPreimage,`Previous code available: ${o}`);const c=le(s.balance,r.balance);return c.overflow?D.error(OB.InvalidService,"Balance overflow"):(this.updatedState.updateServiceInfo(this.currentServiceId,eC.create({...s,balance:c.value})),this.updatedState.stateUpdate.services.servicesRemoved.push(e),D.ok(O))}read(e,t){return null===e?null:this.updatedState.getStorage(e,t)}write(e,t){const r=oe(e.length),s=this.read(this.currentServiceId,e),i=null===s&&null!==t,n=null!==s&&null===t,a=i?1:n?-1:0,o=(t?.length??0)-(s?.length??0),c=i?QB:n?-QB:0n,l=v.isGreaterOrEqual(h.V0_6_7)?i?r:n?-r:0n:0n,d=this.getCurrentServiceInfo(),u=d.storageUtilisationCount+a,f=d.storageUtilisationBytes+BigInt(o)+c+l,g=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,u,f,d);return g.isError?D.error("full",g.details):(this.updatedState.updateStorage(this.currentServiceId,e,t),D.ok(null===s?null:s.length))}lookup(e,t){return null===e?null:this.updatedState.getPreimage(e,t)}}class GB extends _{static Codec=_e.Class(GB,v.isSuite(f.JAMDUNA,h.V0_6_5)?{hash:_e.bytes(Pe).asOpaque(),exportsRoot:_e.bytes(Pe).asOpaque(),authorizerHash:_e.bytes(Pe).asOpaque(),authorizationOutput:_e.blob,payloadHash:_e.bytes(Pe),gas:_e.varU64.asOpaque(),result:Xr.Codec}:{hash:_e.bytes(Pe).asOpaque(),exportsRoot:_e.bytes(Pe).asOpaque(),authorizerHash:_e.bytes(Pe).asOpaque(),payloadHash:_e.bytes(Pe),gas:_e.varU64.asOpaque(),result:Xr.Codec,authorizationOutput:_e.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:a}){return new GB({gas:Dr(s),payloadHash:n.asOpaque(),result:a,authorizationOutput:P.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 GB(e)}}class jB{static Codec=_e.Class(jB,{hash:_e.bytes(Pe).asOpaque(),exportsRoot:_e.bytes(Pe).asOpaque(),authorizerHash:_e.bytes(Pe).asOpaque(),authorizationOutput:_e.blob,payloadHash:_e.bytes(Pe),result:Xr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new jB({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 jB(e)}}class qB{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new qB([],ne(0),Dr(0n))}}class zB{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)??qB.empty();n.reportsLength=ne(n.reportsLength+1),n.gasCost=Dr(n.gasCost+e.gas),n.operands.push(GB.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=Dr(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??ne(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??Dr(0n)}getServiceIds(){return this.serviceIds}}function WB(e){const t=e.map(e=>e.workPackageSpec.hash);return bt.from(t)}const JB=_e.object({serviceId:_e.u32.asOpaque(),entropy:_e.bytes(Pe).asOpaque(),timeslot:_e.u32.asOpaque()});class YB{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(bt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return XB(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>SC.create({report:e,dependencies:this.getWorkReportDependencies(e)})),bt.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=XB(r,WB(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 XB(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return SC.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}const ZB=_e.object({serviceId:_e.u32.convert(e=>e,e=>e),gas:_e.u64.convert(e=>oe(e),e=>Dr(e))});class eR{currentServiceId;index=Ok(0);gasCost=$k(10);tracedRegisters=Nk(7);constructor(e){this.currentServiceId=e}execute(e,t){const r=v.isSuite(f.JAMDUNA,h.V0_6_5)?BigInt(e.get())-10n:e.get();return t.set(7,oe(r)),Promise.resolve(void 0)}}const tR=be(qE.Codec.sizeHint),rR=e=>oe(e);var sR,iR,nR,aR,oR;!function(e){e[e.Void=0]="Void",e[e.ZeroRead=1]="ZeroRead",e[e.ZeroWrite=2]="ZeroWrite",e[e.Read=3]="Read",e[e.Write=4]="Write"}(sR||(sR={})),function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(iR||(iR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(nR||(nR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidOperation=1]="InvalidOperation",e[e.InvalidPage=2]="InvalidPage"}(aR||(aR={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class cR{currentServiceId;fetch;index=Ok(v.selectIfGreaterOrEqual({fallback:18,versions:{[h.V0_6_7]:1}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=oe(s?.length??0),a=he(t.get(8),n),o=he(t.get(9),oe(n-a)),c=null===s?new Uint8Array:s.raw.subarray(Number(a),Number(a+o));if(r.storeFrom(i,c).isError)return Uk.Panic;t.set(7,null===s?S_.NONE:n)}getValue(e){const t=B_(e.get(10));if(t===oR.Constants)return this.fetch.constants();if(t===oR.Entropy)return this.fetch.entropy();if(t===oR.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===oR.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===oR.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===oR.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===oR.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===oR.WorkPackage)return this.fetch.workPackage();if(t===oR.Authorizer)return this.fetch.authorizer();if(t===oR.AuthorizationToken)return this.fetch.authorizationToken();if(t===oR.RefineContext)return this.fetch.refineContext();if(t===oR.AllWorkItems)return this.fetch.allWorkItems();if(t===oR.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===oR.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===oR.AllOperands)return this.fetch.allOperands();if(t===oR.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===oR.AllTransfers)return this.fetch.allTransfers();if(t===oR.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"}(oR||(oR={}));class lR{currentServiceId;account;index=Ok(v.selectIfGreaterOrEqual({fallback:4,versions:{[h.V0_6_7]:5}}));gasCost=$k(10);tracedRegisters=Nk(7,8);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=x_(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),a=null===n?P.empty():Ae.encodeObject(dR,{...n,thresholdBalance:eC.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes,n.gratisStorage)});if(r.storeFrom(i,a.raw).isError)return Uk.Panic;null!==n?t.set(7,S_.OK):t.set(7,S_.NONE)}}const dR=v.isGreaterOrEqual(h.V0_6_7)?_e.object({codeHash:_e.bytes(Pe),balance:_e.u64,thresholdBalance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Dr),onTransferMinGas:_e.u64.convert(e=>e,Dr),storageUtilisationBytes:_e.u64,storageUtilisationCount:_e.u32,gratisStorage:_e.u64,created:_e.u32.convert(e=>e,Ur),lastAccumulation:_e.u32.convert(e=>e,Ur),parentService:_e.u32.convert(e=>e,Nr)},"ServiceAccountInfoWithThresholdBalance"):_e.object({codeHash:_e.bytes(Pe),balance:_e.varU64,thresholdBalance:_e.varU64,accumulateMinGas:_e.varU64.convert(e=>e,Dr),onTransferMinGas:_e.varU64.convert(e=>e,Dr),storageUtilisationBytes:_e.varU64,storageUtilisationCount:_e.varU32,gratisStorage:ZE(oe(0)),created:ZE(Ur(0)),lastAccumulation:ZE(Ur(0)),parentService:ZE(Nr(0))},"ServiceAccountInfoWithThresholdBalance"),uR=Xs.new(void 0,"host-calls"),hR=new TextDecoder("utf8");class fR{currentServiceId;index=Ok(100);gasCost=$k(0);tracedRegisters=Nk();constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),a=t.get(10),o=t.get(11),c=new Uint8Array(B_(n)),l=new Uint8Array(B_(o));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,a),uR.trace(`[${this.currentServiceId}] [${s}] ${hR.decode(c)} ${hR.decode(l)}`),Promise.resolve(void 0)}}class gR{currentServiceId;account;index=Ok(v.selectIfGreaterOrEqual({fallback:1,versions:{[h.V0_6_7]:2}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=x_(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=L.zero(Pe);if(r.loadInto(a.raw,i).isError)return Uk.Panic;const o=this.account.lookup(s,a),c=oe(null===o?0:o.raw.length),l=t.get(10),d=t.get(11),u=he(l,c),h=he(d,oe(c-u)),f=null===o?new Uint8Array(0):o.raw.subarray(Number(u),Number(u+h));if(r.storeFrom(n,f).isError)return Uk.Panic;null!==o?t.set(7,c):t.set(7,S_.NONE)}}class pR{currentServiceId;account;index=Ok(v.selectIfGreaterOrEqual({fallback:2,versions:{[h.V0_6_7]:3}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=x_(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=t.get(10),o=B_(n),c=new Uint8Array(o);if(r.loadInto(c,i).isError)return Uk.Panic;const l=this.account.read(s,P.blobFrom(c)),d=oe(null===l?0:l.raw.length),u=t.get(11),h=t.get(12),f=he(u,d),g=he(h,oe(d-f)),p=null===l?new Uint8Array(0):l.raw.subarray(Number(f),Number(f+g));if(r.storeFrom(a,p).isError)return Uk.Panic;null!==l?t.set(7,d):t.set(7,S_.NONE)}}class bR{currentServiceId;account;index=Ok(v.selectIfGreaterOrEqual({fallback:3,versions:{[h.V0_6_7]:4}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,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),a=t.get(10),o=B_(i),c=new Uint8Array(o);if(r.loadInto(c,s).isError)return Uk.Panic;const l=P.blobFrom(c),d=B_(a),u=new Uint8Array(d);if(r.loadInto(u,n).isError)return Uk.Panic;const h=0n===a?null:P.blobFrom(u),f=this.account.write(l,h);f.isError?t.set(7,S_.FULL):t.set(7,null===f.ok?S_.NONE:oe(f.ok))}}const mR=[class{currentServiceId;partialState;chainSpec;index=Ok(v.selectIfGreaterOrEqual({fallback:5,versions:{[h.V0_6_7]:14}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,10,11);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=__(t.get(9)),a=t.get(10),o=t.get(11),c=new Array,l=new Uint8Array(be(ZB.sizeHint)),d=fe.fromBlob(l);let u=a;for(let e=0n;e<o;e+=1n){if(d.resetTo(0),r.loadInto(l,u).isError)return Uk.Panic;const{serviceId:e,gas:t}=d.object(ZB);c.push([e,t]),u=oe(u+oe(d.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,RE(new Array(this.chainSpec.coresCount).fill(i),this.chainSpec),n,c),t.set(7,S_.OK)):t.set(7,S_.WHO)}},class{currentServiceId;partialState;chainSpec;index=Ok(v.selectIfGreaterOrEqual({fallback:6,versions:{[h.V0_6_7]:15}}));gasCost=$k(10);tracedRegisters=Nk(7,8);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 Uk.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,S_.CORE);const a=fe.fromBlob(n).sequenceFixLen(_e.bytes(Pe),80),o=yt.new(a,80);t.set(7,S_.OK),this.partialState.updateAuthorizationQueue(Mr(Number(s)),o)}},class{currentServiceId;partialState;chainSpec;index=Ok(v.selectIfGreaterOrEqual({fallback:7,versions:{[h.V0_6_7]:16}}));gasCost=$k(10);tracedRegisters=Nk(7);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(tR*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return Uk.Panic;const n=fe.fromBlob(i).sequenceFixLen(qE.Codec,this.chainSpec.validatorsCount);t.set(7,S_.OK),this.partialState.updateValidatorsData(Lr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:8,versions:{[h.V0_6_7]:17}}));gasCost=$k(10);tracedRegisters;gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new eR(e),this.tracedRegisters=this.gasHostCall.tracedRegisters}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:9,versions:{[h.V0_6_7]:18}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Dr(t.get(9)),a=Dr(t.get(10)),o=v.isGreaterOrEqual(h.V0_6_7)?t.get(11):oe(0),c=L.zero(Pe);if(r.loadInto(c.raw,s).isError)return Uk.Panic;const l=this.partialState.newService(c.asOpaque(),i,n,a,o);if(l.isOk)return void t.set(7,oe(l.ok));const d=l.error;d!==TB.InsufficientFunds?d!==TB.UnprivilegedService?E(d):t.set(7,S_.HUH):t.set(7,S_.CASH)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:10,versions:{[h.V0_6_7]:19}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9);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),a=L.zero(Pe);if(r.loadInto(a.raw,s).isError)return Uk.Panic;this.partialState.upgradeService(a.asOpaque(),i,n),t.set(7,S_.OK)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:11,versions:{[h.V0_6_7]:20}}));gasCost=e=>{const t=10n+e.get(9);return jk(t)};tracedRegisters=Nk(7,8,9,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=Dr(t.get(9)),a=t.get(10),o=L.zero(128);if(r.loadInto(o.raw,a).isError)return Uk.Panic;const c=this.partialState.transfer(s,i,n,o);if(c.isOk)return void t.set(7,S_.OK);const l=c.error;l!==RB.DestinationNotFound?l!==RB.GasTooLow?l!==RB.BalanceBelowThreshold?E(l):t.set(7,S_.CASH):t.set(7,S_.LOW):t.set(7,S_.WHO)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:12,versions:{[h.V0_6_7]:21}}));gasCost=$k(10);tracedRegisters=Nk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=__(t.get(7)),i=t.get(8),n=L.zero(Pe).asOpaque();if(r.loadInto(n.raw,i).isError)return Uk.Panic;if(s===this.currentServiceId)return void t.set(7,S_.WHO);const a=this.partialState.eject(s,n);if(a.isOk)return void t.set(7,S_.OK);const o=a.error;o===OB.InvalidService?t.set(7,S_.WHO):o===OB.InvalidPreimage?t.set(7,S_.HUH):E(o)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:13,versions:{[h.V0_6_7]:22}}));gasCost=$k(10);tracedRegisters=Nk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Uk.Panic;const a=this.partialState.checkPreimageStatus(n.asOpaque(),i),o=oe(0n);if(null===a)return t.set(7,S_.NONE),void t.set(8,o);switch(a.status){case xB.Requested:return t.set(7,o),void t.set(8,o);case xB.Available:return t.set(7,oe(1n+(BigInt(a.data[0])<<32n))),void t.set(8,o);case xB.Unavailable:return t.set(7,oe(2n+(BigInt(a.data[0])<<32n))),void t.set(8,oe(a.data[1]));case xB.Reavailable:return t.set(7,oe(3n+(BigInt(a.data[0])<<32n))),void t.set(8,oe((BigInt(a.data[2])<<32n)+BigInt(a.data[1])))}}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:14,versions:{[h.V0_6_7]:23}}));gasCost=$k(10);tracedRegisters=Nk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Uk.Panic;const a=this.partialState.requestPreimage(n.asOpaque(),i);if(a.isOk)return void t.set(7,S_.OK);const o=a.error;o!==_B.AlreadyAvailable&&o!==_B.AlreadyRequested?o!==_B.InsufficientFunds?E(o):t.set(7,S_.FULL):t.set(7,S_.HUH)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:15,versions:{[h.V0_6_7]:24}}));gasCost=$k(10);tracedRegisters=Nk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Uk.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,S_.OK):t.set(7,S_.HUH)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:16,versions:{[h.V0_6_7]:25}}));gasCost=$k(10);tracedRegisters=Nk(7);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=L.zero(Pe);if(r.loadInto(i.raw,s).isError)return Uk.Panic;this.partialState.yield(i),t.set(7,S_.OK)}},class{currentServiceId;partialState;index=Ok(v.selectIfGreaterOrEqual({fallback:27,versions:{[h.V0_6_7]:26}}));gasCost=$k(10);tracedRegisters=Nk(7,8,9);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=x_(7,t,this.currentServiceId),i=t.get(8),n=B_(t.get(9)),a=P.blobFrom(new Uint8Array(n));if(r.loadInto(a.raw,i).isError)return Uk.Panic;const o=this.partialState.providePreimage(s,a);if(o.isOk)return void t.set(7,S_.OK);const c=o.error;c!==UB.ServiceNotFound?c!==UB.WasNotRequested&&c!==UB.AlreadyProvided?E(c):t.set(7,S_.HUH):t.set(7,S_.WHO)}}];var yR,AR;!function(e){e.IS_AUTHORIZED=rR(0),e.REFINE=rR(0),e.ACCUMULATE=rR(5),e.ON_TRANSFER=rR(10)}(yR||(yR={}));class IR{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new w_(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new O_(...t),this.pvm=new v_(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=mR.map(s=>new s(e,t.partialState,r)),i=[new fR(e),new eR(e),new pR(e,t.serviceExternalities),new bR(e,t.serviceExternalities),new cR(e,t.fetchExternalities),new gR(e,t.serviceExternalities),new lR(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new fR(e),new eR(e),new cR(e,t.fetchExternalities),new pR(e,t.partialState),new bR(e,t.partialState),new gR(e,t.partialState),new lR(e,t.partialState)]}async run(e,t){const r=F_.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=IR.prepareAccumulateHostCalls(e,r,s);return new IR(t,i,yR.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=IR.prepareOnTransferHostCalls(e,r);return new IR(t,s,yR.ON_TRANSFER)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(AR||(AR={}));const vR=10000000n,wR=Xs.new(void 0,"accumulate"),SR=_e.object({slot:_e.u32.asOpaque(),serviceId:_e.u32.asOpaque(),operands:_e.sequenceVarLen(jB.Codec)}),ER=_e.object({slot:_e.u32.asOpaque(),serviceId:_e.u32.asOpaque(),operands:_e.sequenceVarLen(GB.Codec)}),CR=_e.object({slot:_e.varU32.asOpaque(),serviceId:_e.varU32.asOpaque(),operands:_e.varU32});class kR{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 a=this.state.getService(t);if(null===a)return wR.log(`Service with id ${t} not found.`),D.error(AR.NoService);const o=a.getInfo().codeHash,c=a.getPreimage(o.asOpaque());if(null===c)return wR.log(`Code with hash ${o} not found for service ${t}.`),D.error(AR.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=ue(qe(Ae.encodeObject(JB,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return Nr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),d=new $B(this.chainSpec,new VB(this.state,n),t,l,e),u={partialState:d,serviceExternalities:d,fetchExternalities:DR.createForAccumulate({entropy:i,operands:r},this.chainSpec)},f=IR.createAccumulateExecutor(t,c,u,this.chainSpec);let g=P.empty();g=v.is(h.V0_6_4)?Ae.encodeObject(SR,{slot:e,serviceId:t,operands:r},this.chainSpec):v.is(h.V0_6_5)?Ae.encodeObject(ER,{slot:e,serviceId:t,operands:r},this.chainSpec):Ae.encodeObject(CR,{slot:e,serviceId:t,operands:ne(r.length)});const p=await f.run(g,jk(s)),[b,m]=d.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===kk.OOG||e===kk.PANIC)return D.ok({stateUpdate:m,consumedGas:Dr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Pe){const e=L.fromBlob(p.memorySlice,Pe);b.yieldedRoots.set(t,e.asOpaque())}return D.ok({stateUpdate:b,consumedGas:Dr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){wR.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const a=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return a.isError?(wR.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(wR.trace(`Accumulation successful for ${e}. Consumed: ${a.ok.consumedGas}`),a.ok)}async accumulateSequentially(e,t,r,s,i,n){const a=this.findReportCutoffIndex(e,t);if(0===a)return{accumulatedReports:ne(0),gasCost:Dr(0),state:n};const o=t.slice(0,a),c=this.state.privilegedServices.autoAccumulateServices,l=new zB(o,c),d=t.slice(a),{gasCost:u,state:h,...f}=await this.accumulateInParallel(l,r,s,i,n);C(f);const{accumulatedReports:g,gasCost:p,state:b,...m}=await this.accumulateSequentially(Dr(e-u),d,r,s,i,h);return C(m),{accumulatedReports:ne(a+g),gasCost:Dr(u+p),state:b}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds();let a=Dr(0),o=i;for(const i of n){const n=HB.copyFrom(o),{consumedGas:c,stateUpdate:l}=await this.accumulateSingleService(i,e.getOperands(i),e.getGasCost(i),t,r,o);a=Dr(a+c);const d=s.get(i)??{count:ne(0),gasUsed:Dr(0)};d.count=ne(d.count+e.getReportsLength(i)),d.gasUsed=Dr(d.gasUsed+c),s.set(i,d),o=null===l?n:l}return{state:o,gasCost:a}}getAccumulationStateUpdate(e,t,r,s,i){const n=this.chainSpec.epochLength,a=r%n,o=WB(e),c=Array.from(o).sort((e,t)=>DE(e,t).value),l=Vr(this.state.recentlyAccumulated.slice(1).concat(bt.from(c)),this.chainSpec),d=this.state.accumulationQueue.slice();d[a]=XB(t,o);for(let e=1;e<n;e++){const t=(a+n-e)%n;e<r-this.state.timeslot?d[t]=[]:d[t]=XB(d[t],o)}const u=new VB(this.state,HB.new(i));if(v.isGreaterOrEqual(h.V0_6_7))for(const e of s){const t=u.getServiceInfo(e);null!==t&&u.updateServiceInfo(e,eC.create({...t,lastAccumulation:r}))}return{recentlyAccumulated:l,accumulationQueue:Vr(d,this.chainSpec),timeslot:r,...u.stateUpdate.services}}getGasLimit(){const e=vR*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Dr(this.chainSpec.maxBlockGas>e?this.chainSpec.maxBlockGas:e);return Dr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new YB(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),a=i.getWorkReportsToAccumulateLater(e),o=XB(i.getQueueFromState(t).concat(a),WB(n)),c=i.enqueueReports(o),l=n.concat(c),d=this.getGasLimit(),{accumulatedReports:u,gasCost:h,state:f,...g}=await this.accumulateSequentially(d,l,t,r,s,HB.empty());C(g);const p=l.slice(0,u),{services:b,yieldedRoots:m,transfers:y,validatorsData:A,privilegedServices:I,authorizationQueues:v,...w}=f;C(w);const S=this.getAccumulationStateUpdate(p,a,t,Array.from(s.keys()),b),E=await async function(e){const t=await ft.create(),r=(s=t,{hashConcat:(e,t=[])=>gt(s,[e,...t].map(P.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 L.zero(Pe).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(P.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>P.blobFromParts([de(e),t.raw])),r)}(Array.from(m.entries())),k=(()=>{if(0===v.size)return{};const e=this.state.authQueues.slice();for(const[t,r]of v.entries())e[t]=r;return{authQueues:RE(e,this.chainSpec)}})();return D.ok({root:E,stateUpdate:{...S,...null===A?{}:{designatedValidatorData:A},...null===I?{}:{privilegedServices:I},...k},accumulationStatistics:s,pendingTransfers:y})}}var xR;!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"}(xR||(xR={}));class _R{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=yt.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:a,bitfield:o}=r;if(!s.isEqualTo(e.parentHash))return D.error(xR.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=a)return D.error(xR.InvalidOrder,`order: expected: ${n+1}, got: ${a}`);n=r.validatorIndex,w(o.bitLength===t,`Invalid bitfield length of ${o.bitLength}`);const c=o.indicesOfSetBits();for(const e of c)i[e]+=1}const a=[],o=[],c=this.chainSpec.validatorsSuperMajority,l=e.disputesAvailAssignment.slice();for(let r=0;r<t;r++){const t=i[r],s=l[r],n=null!==s;if(t>0&&!n)return D.error(xR.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&o.push(r),t>=c&&(a.push(s.workReport.data),o.push(r)))}const d=await r;if(d.isError)return d;for(const e of o)l[e]=null;return D.ok({availableReports:a,stateUpdate:{availabilityAssignment:l}})}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 D.error(xR.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:RR(e.anchor.encoded(),e.bitfield.encoded())})}const s=await wr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return D.error(xR.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return D.ok(O)}}const BR=P.blobFromString("jam_available").raw;function RR(e,t){return P.blobFromParts(BR,qe(P.blobFromParts(e.raw,t.raw)).raw)}var OR;!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",e[e.BannedValidator=23]="BannedValidator"}(OR||(OR={}));const UR=_e.object({B_I:_e.u64,B_L:_e.u64,B_S:_e.u64,C:_e.u16,D:_e.u32,E:_e.u32,G_A:_e.u64,G_I:_e.u64,G_R:_e.u64,G_T:_e.u64,H:_e.u16,I:_e.u16,J:_e.u16,K:_e.u16,L:_e.u32,N:_e.u16,O:_e.u16,P:_e.u16,Q:_e.u16,R:_e.u16,T:_e.u16,U:_e.u16,V:_e.u16,W_A:_e.u32,W_B:_e.u32,W_C:_e.u32,W_E:_e.u32,W_M:_e.u32,W_P:_e.u32,W_R:_e.u32,W_T:_e.u32,W_X:_e.u32,Y:_e.u32}),TR=new Map;var NR;!function(e){e[e.Accumulate=0]="Accumulate",e[e.OnTransfer=1]="OnTransfer"}(NR||(NR={}));class DR{fetchData;chainSpec;constructor(e,t){this.fetchData=e,this.chainSpec=t}static createForAccumulate(e,t){return new DR({context:NR.Accumulate,...e},t)}static createForOnTransfer(e,t){return new DR({context:NR.OnTransfer,...e},t)}constants(){return function(e){const t=TR.get(e);if(void 0!==t)return t;const r=Ae.encodeObject(UR,{B_I:oe(10n),B_L:oe(1n),B_S:oe(100n),C:se(e.coresCount),D:ne(e.preimageExpungePeriod),E:ne(e.epochLength),G_A:oe(vR),G_I:oe(5e7),G_R:oe(e.maxRefineGas),G_T:oe(e.maxBlockGas),H:se(8),I:se(zr),J:se(8),K:se(16),L:ne(14400),N:se(2),O:se(8),P:se(e.slotDuration),Q:se(80),R:se(e.rotationPeriod),T:se(128),U:se(5),V:e.validatorsCount,W_A:ne(64e3),W_B:ne(13794305),W_C:ne(4e6),W_E:ne(e.erasureCodedPieceSize),W_M:ne(3072),W_P:ne(e.numberECPiecesPerSegment),W_R:ne(49152),W_T:ne(128),W_X:ne(3072),Y:ne(e.contestLength)});return TR.set(e,r),r}(this.chainSpec)}entropy(){const{entropy:e}=this.fetchData;return void 0===e?null:e.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(){if(this.fetchData.context!==NR.Accumulate)return null;const e=this.fetchData.operands;return v.is(h.V0_6_4)?Ae.encodeObject(_e.sequenceVarLen(jB.Codec),e,this.chainSpec):Ae.encodeObject(_e.sequenceVarLen(GB.Codec),e,this.chainSpec)}oneOperand(e){if(this.fetchData.context!==NR.Accumulate)return null;const{operands:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:v.isGreaterOrEqual(h.V0_6_5)?Ae.encodeObject(GB.Codec,r,this.chainSpec):Ae.encodeObject(jB.Codec,r,this.chainSpec)}allTransfers(){if(this.fetchData.context!==NR.OnTransfer)return null;const{transfers:e}=this.fetchData;return Ae.encodeObject(_e.sequenceVarLen(PB.Codec),e,this.chainSpec)}oneTransfer(e){if(this.fetchData.context!==NR.OnTransfer)return null;const{transfers:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ae.encodeObject(PB.Codec,r,this.chainSpec)}}const MR=_e.object({timeslot:_e.u32.asOpaque(),serviceId:_e.u32.asOpaque(),transfers:_e.sequenceVarLen(PB.Codec)}),PR=_e.object({timeslot:_e.varU32.asOpaque(),serviceId:_e.varU32.asOpaque(),transfersLength:_e.varU32});var LR;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(LR||(LR={}));const HR=Xs.new(void 0,"deferred-transfers");class VR{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition({pendingTransfers:e,timeslot:t,servicesUpdate:r,entropy:s}){const i=new Map,n=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]));let a=HB.new(r);for(const r of n){const n=new VB(this.state,a),o=e.filter(e=>e.destination===r),c=n.getServiceInfo(r);if(null===c)return D.error(LR.ServiceInfoNotExist);const l=c.codeHash,d=n.getPreimage(r,l.asOpaque()),u=le(c.balance,...o.map(e=>e.amount));if(u.overflow)return D.error(LR.ServiceBalanceOverflow);const f=eC.create({...c,balance:u.value});n.updateServiceInfo(r,f);const g=new $B(this.chainSpec,n,r,r,t),p=DR.createForOnTransfer({entropy:s,transfers:o},this.chainSpec);let b=jk(0);if(null===d||0===o.length)HR.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`);else{const e=()=>v.isGreaterOrEqual(h.V0_6_7)?Ae.encodeObject(PR,{timeslot:t,serviceId:r,transfersLength:ne(o.length)},this.chainSpec):Ae.encodeObject(MR,{timeslot:t,serviceId:r,transfers:o},this.chainSpec),s=IR.createOnTransferExecutor(r,d,{partialState:g,fetchExternalities:p}),i=e(),n=o.reduce((e,t)=>e+t.gas,0n);b=(await s.run(i,jk(n))).consumedGas}i.set(r,{count:ne(o.length),gasUsed:Dr(b)});const[m,y]=g.getStateUpdates();a=m,w(null===y,"On transfer cannot invoke checkpoint.")}return D.ok({servicesUpdate:a.services,transferStatistics:i})}}class KR{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]=mt(s)}return{authPools:RE(t,this.chainSpec)}}}class QR{hasher;state;constructor(e,t){this.hasher=e,this.state=t}partialTransition(e){const t=this.state.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null;return null!==r&&(r.postStateRoot=e.priorStateRoot),{recentBlocks:this.state.recentBlocks.updateBlocks(t)}}transition(e){const t=e.partial.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null,s=v.isGreaterOrEqual(h.V0_6_7)?null!==this.state.recentBlocks.asCurrent().accumulationLog?HE.fromPeaks(this.hasher,this.state.recentBlocks.asCurrent().accumulationLog):HE.empty(this.hasher):null!==r?HE.fromPeaks(this.hasher,r.mmr):HE.empty(this.hasher);s.append(e.accumulateRoot);const i=s.getPeaks();return v.isGreaterOrEqual(h.V0_6_7)?t.push(FE.create({headerHash:e.headerHash,accumulationResult:s.getSuperPeakHash(),postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})):t.push(KE.create({headerHash:e.headerHash,mmr:i,postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})),t.length>8&&t.shift(),{recentBlocks:v.isGreaterOrEqual(h.V0_6_7)?GE.create($E.create({blocks:t,accumulationLog:i})):GE.legacyCreate(QE.create({blocks:t}))}}}function FR(e,t,r){return function(e,t,r){const s=$R(Ur(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){w(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(de(ne(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=ue(qe(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),a=s,o=r.coresCount,n.map(e=>(e+a)%o));var n,a,o;return i}(t,r,e)}function $R(e,t){return Math.floor(e/t)}const GR=P.blobFromString("jam_guarantee").raw;function jR(e){return P.blobFromParts(GR,e.raw)}const qR=1e7;class zR{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 D.error(OR.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return D.error(OR.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return D.ok(O)}(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 D.error(OR.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 D.error(OR.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return D.ok(O)}(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=wr(i.ok),a=this.verifyPostSignatureChecks(e.guarantees,e.assurancesAvailAssignment);if(a.isError)return a;const o=this.verifyContextualValidity(e);if(o.isError)return o;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const d=e.assurancesAvailAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];d[r.coreIndex]=BE.create({workReport:new He(i,r),timeout:e.slot}),l+=1}const u=It.fromArray(W,i.ok.map(e=>e.key)).slice();return function(e,t){for(const r of e)if(t.has(r))return!0;return!1}(u,e.offenders)?D.error(OR.BannedValidator):D.ok({stateUpdate:{availabilityAssignment:RE(d,this.chainSpec)},reported:o.ok,reporters:u})}workReportHashes(e){const t=[];for(const r of e)t.push(B(qe(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let a=0;for(const r of e){const e=r.view(),o=e.report.view().coreIndex.materialize(),c=t[a];a+=1;const l=e.credentials.view();if(l.length<is[0]||l.length>is[1])return D.error(OR.InsufficientGuarantees,`Invalid number of credentials. Expected ${is}, got ${l.length}`);const d=s(n,e.slot.materialize());if(d.isError)return d;const u=d.ok;let h=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(h>=r)return D.error(OR.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${h+1}`);h=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return D.error(OR.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==o)return D.error(OR.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${o}`);i.push({signature:s,key:n.ed25519,message:jR(c)})}}return D.ok(i)}(e.guarantees,t,e.slot,(t,r)=>this.getGuarantorAssignment(t,r,e.newEntropy))}verifyPostSignatureChecks(e,t){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return D.error(OR.CoreEngaged,`Report pending availability at core: ${n}`);const a=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(a)))return D.error(OR.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${a}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return D.error(OR.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return D.error(OR.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const o=le(...e.results.map(e=>e.gas));if(o.overflow||o.value>qR)return D.error(OR.WorkReportGasTooHigh,`Total gas too high. Got: ${o.value} (ovfl: ${o.overflow}), maximal: ${qR}`)}return D.ok(O)}(e,t,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=pt.new(),a=bt.new(),o=bt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=rs.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),a.insertAll(e.report.context.prerequisites),o.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 D.error(OR.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return D.error(OR.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return D.error(OR.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=pt.new();for(const e of r.blocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return D.error(OR.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return D.error(OR.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const a=GE.accumulationResult(t,{hasher:s});if(!a.isEqualTo(r.beefyRoot))return D.error(OR.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${a}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return D.error(OR.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return D.error(OR.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return D.ok(O)}(Math.max(0,e.slot-14400),i,e.recentBlocksPartialUpdate,r,s);if(c.isError)return c;const l=function(e,t){const r=bt.new();for(const e of t.recentBlocks.blocks)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 D.error(OR.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return D.ok(O)}(bt.viewDictionaryKeys(n),t);if(l.isError)return l;const d=pt.new();for(const e of t.recentBlocks.blocks)for(const t of e.reported.values())d.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 D.error(s?OR.SegmentRootLookupInvalid:OR.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return D.ok(O)},n=i(r);if(n.isError)return n;const a=i(s,!0);return a.isError?a:D.ok(O)}({currentWorkPackages:n,recentlyReported:d,prerequisiteHashes:a,segmentRootLookupHashes:o});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=d.get(t.workPackageHash);e=void 0!==r?rs.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return D.error(OR.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return D.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return D.ok(O);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return D.error(OR.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=$R(e,i),a=$R(t,i),o=Math.max(0,n-1)*i;if(t>e)return D.error(OR.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return D.error(OR.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,d=e;n>a&&(d=Ur(e-i),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(d,e,s)&&(c=r[3],l=this.state.previousValidatorData));const u=FR(this.chainSpec,c,d);return D.ok((h=l,f=(e,t)=>({core:e,ed25519:t.ed25519}),u.map((e,t)=>f(e,h[t]))));var h,f}}class WR{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=Lr(Array.from({length:this.chainSpec.validatorsCount},()=>hC.empty()),this.chainSpec);return mC.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return ne(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),ne(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:Dr(t.gasUsed),exported:se(t.exported),imported:se(t.imported),extrinsicCount:se(t.extrinsicCount),extrinsicSize:ne(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:se(t.count),size:ne(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,a=this.getStatistics(t),{current:o,cores:c,services:l}=a;w(void 0!==o[r],"authorIndex is out of bounds");const d=o[r].blocks+1;o[r].blocks=ne(d);const u=o[r].tickets+s.tickets.length;o[r].tickets=ne(u);const h=o[r].preImages+s.preimages.length;o[r].preImages=ne(h);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),g=o[r].preImagesSize+f;o[r].preImagesSize=ne(g);const p=new Set;for(const e of s.guarantees)for(const{validatorIndex:t}of e.credentials)if(!p.has(t)){const e=o[t].guarantees+1;o[t].guarantees=ne(e),p.add(t)}for(const{validatorIndex:e}of s.assurances){const t=o[e].assurances+1;o[e].assurances=ne(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Mr(e),r=i.find(e=>e.coreIndex===t),{imported:a,extrinsicCount:o,extrinsicSize:l,exported:d,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:se(0),extrinsicCount:se(0),extrinsicSize:ne(0),exported:se(0),gasUsed:Dr(0n)},h=n.find(e=>e.coreIndex===t),f=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=a,c[t].extrinsicCount=o,c[t].extrinsicSize=l,c[t].exports=d,c[t].gasUsed=u,c[t].bundleSize=ne(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(h),c[t].popularity=se(f)}l.clear();const b=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of b){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:a,extrinsicCount:o,extrinsicSize:c,exported:d}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:h,size:f}=this.calculateProvidedScoreService(u),{count:g,gasUsed:p}=e.accumulationStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},{count:b,gasUsed:m}=e.transferStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},y=bC.empty();y.refinementCount=ne(r.length),y.refinementGasUsed=n,y.imports=a,y.extrinsicCount=o,y.extrinsicSize=c,y.exports=d,y.providedCount=h,y.providedSize=f,y.providedCount=h,y.providedSize=f,y.accumulateCount=g,y.accumulateGasUsed=p,y.onTransfersCount=b,y.onTransfersGasUsed=m,l.set(t,y)}return{statistics:a}}}class JR{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}const YR="offenders not matching header";var XR;!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",e[e.Offenders=8]="Offenders"}(XR||(XR={}));const ZR=(e,t)=>D.taggedError(XR,e,t);class eO{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=SB.new({synchronous:!i});this.statistics=new WR(e,t),this.safrole=new NB(e,t,n),this.safroleSeal=new DB(n),this.recentHistory=new QR(s,t),this.disputes=new oB(e,t),this.reports=new zR(e,t,s,new JR(r)),this.assurances=new _R(e,t),this.accumulate=new kR(e,t),this.deferredTransfers=new VR(e,t),this.preimages=new W_(t),this.authorization=new KR(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 a=r;if(s&&(a=qe(i.seal).asOpaque()),null===a){const t=await this.verifySeal(n,e);if(t.isError)return ZR(XR.SafroleSeal,t);a=t.ok}const o=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(o.isError)return ZR(XR.Disputes,o);const{stateUpdate:{disputesRecords:c,availabilityAssignment:l,...d},offendersMark:u}=o.ok;C(d);const h=function(e,t){if(e.size!==t.length)return D.error(YR,`Length mismatch: ${e.size} vs ${t.length}`);for(const r of t)if(!e.has(r))return D.error(YR,`Missing key: ${r}`);return D.ok(O)}(u,e.header.view().offendersMarker.materialize());if(h.isError)return ZR(XR.Offenders,h);const f=await this.safrole.transition({slot:n,entropy:a,extrinsic:e.extrinsic.view().tickets.materialize(),punishSet:c.punishSet});if(f.isError)return ZR(XR.Safrole,f);const{timeslot:g,ticketsAccumulator:p,sealingKeySeries:b,epochRoot:m,entropy:y,nextValidatorData:A,currentValidatorData:I,previousValidatorData:v,...w}=f.ok.stateUpdate;C(w);const S=this.recentHistory.partialTransition({priorStateRoot:i.priorStateRoot}),{recentBlocks:E,...k}=S;C(k);const x=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash,disputesAvailAssignment:l});if(x.isError)return ZR(XR.Assurances,x);const{availableReports:_,stateUpdate:B,...R}=x.ok;C(R);const{availabilityAssignment:U,...T}=B;C(T);const N=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),newEntropy:y,recentBlocksPartialUpdate:E,assurancesAvailAssignment:U,offenders:u});if(N.isError)return ZR(XR.Reports,N);const{reported:M,reporters:P,stateUpdate:L,...H}=N.ok;C(H);const{availabilityAssignment:V,...K}=L;C(K);const Q=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(Q.isError)return ZR(XR.Preimages,Q);const{preimages:F,...$}=Q.ok;C($);const G=await this.accumulate.transition({slot:n,reports:_,entropy:y[0]});if(G.isError)return ZR(XR.Accumulate,G);const{root:j,stateUpdate:q,accumulationStatistics:z,pendingTransfers:W,...J}=G.ok;C(J);const{privilegedServices:Y,authQueues:X,designatedValidatorData:Z,timeslot:ee,preimages:te,accumulationQueue:re,recentlyAccumulated:se,...ie}=q,ne=await this.deferredTransfers.transition({entropy:y[0],pendingTransfers:W,servicesUpdate:{...ie,preimages:te},timeslot:n});if(ne.isError)return ZR(XR.DeferredTransfers,ne);const{servicesUpdate:ae,transferStatistics:oe,...ce}=ne.ok;C(ce);const le=this.recentHistory.transition({partial:S,headerHash:t,accumulateRoot:j,workPackages:M}),{recentBlocks:de,...ue}=le;C(ue);const he=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:fe,...ge}=he;C(ge);const pe=e.extrinsic.materialize(),be=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:pe,incomingReports:pe.guarantees.map(e=>e.report),availableReports:_,accumulationStatistics:z,transferStatistics:oe}),{statistics:me,...ye}=be;return C(ye),D.ok({...void 0!==X?{authQueues:X}:{},...void 0!==Z?{designatedValidatorData:Z}:{},...void 0!==Y?{privilegedServices:Y}:{},authPools:fe,disputesRecords:c,availabilityAssignment:V,recentBlocks:de,statistics:me,timeslot:g,epochRoot:m,entropy:y,currentValidatorData:I,nextValidatorData:A,previousValidatorData:v,sealingKeySeries:b,ticketsAccumulator:p,accumulationQueue:re,recentlyAccumulated:se,...ae,preimages:F.concat(te)})}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)??bt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}var tO;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(tO||(tO={}));const rO=(e,t)=>D.taggedError(tO,e,t);class sO{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(),a=i.getState(n);if(null===a)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new X_(t,s),this.stf=new eO(e,a,s,t,{enableParallelSealVerification:!0}),this.state=a,r.info(`😎 Best time slot: ${a.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: ${N(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=x("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return rO(tO.Verifier,n);const a=e.header.view().timeSlotIndex.materialize(),o=n.ok;s.log(`🧱 Verified block: Got hash ${o} for block at slot ${a}.`);const c=x("import:stf"),l=await this.stf.transition(e,o,t,r);if(s.log(c()),l.isError)return rO(tO.Stf,l);const d=l.ok,u=x("import:state"),h=await this.states.updateAndSetState(o,this.state,d);if(h.isError)return s.error(`🧱 Unable to update state: ${N(h)}`),rO(tO.Update,h);const f=this.states.getState(o);if(null===f)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(f.backend),s.log(u());const g=x("import:db"),p=this.blocks.insertBlock(new He(o,e)),b=await this.states.getStateRoot(f);s.log(`🧱 Storing post-state-root for ${o}: ${b}.`);const m=this.blocks.setPostStateRoot(o,b);return await Promise.all([p,m]),s.log(g()),await this.blocks.setBestHeaderHash(o),D.ok(new He(o,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const iO=Xs.new(void 0,"importer");class nO extends hk{onBestBlock=new lk;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=fe.decodeObject(fs,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 aO extends hk{onBlock=new lk;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=Ae.encodeObject(fs,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(ms.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else iO.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 oO=Xs.new(void 0,"importer");if(!IE.isMainThread){Xs.configureAll(process.env.JAM_LOG??"",Fs.LOG);const e=function(){const e=new pk("ready(importer)",Ct.reInit),t=new aO,r=new fk;return new dk("importer",e,[e,t,r])}();ak.receiveChannel(e,IE.parentPort).then(e=>async function(e){oO.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{oO.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new kE(r.dbPath),i=new wE(r.chainSpec,s),n=new ZC(r.chainSpec,s),a=new sO(r.chainSpec,new z_(r.chainSpec,await cO,new Ke),oO,i,n);let o=!1;const c=new J_(r.chainSpec,a);e.onBlock.on(async s=>{const n=J_.getBlockDetails(s);if(n.isError)oO.trace("🧊 Ignoring invalid block.");else if(null===i.getHeader(n.ok.hash)){if(c.push(n.ok).isError)oO.trace(`🧊 Already queued block: #${n.ok.data.timeSlot}.`);else if(oO.log(`🧊 Queued block: #${n.ok.data.timeSlot}`),!o){o=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:o}=s,l=x("importBlock"),d=await a.importBlock(i,await n,r.omitSealVerification);if(d.isOk){const r=d.ok;e.announce(t,r),oO.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else oO.log(`❌ Rejected block #${o}: ${N(d)}`);oO.log(l())}}finally{o=!1}}}else oO.trace(`🧊 Already imported block: #${n.ok.data.timeSlot}.`)})});oO.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>oO.error(e))}const cO=ft.create(),lO=Xs.new(void 0,"net:worker");class dO{genericConfig;genesisHeaderHash;key;host;port;bootnodes;static reInit(e){const{genericConfig:t,genesisHeaderHash:r,key:s,host:i,port:n,bootnodes:a}=e;return new dO(Ct.reInit(t),L.fromBlob(r.raw,Pe).asOpaque(),L.fromBlob(s.raw,32).asOpaque(),i,n,a)}static new({genericConfig:e,genesisHeaderHash:t,key:r,host:s,port:i,bootnodes:n}){return new dO(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.genericConfig=e,this.genesisHeaderHash=t,this.key=r,this.host=s,this.port=i,this.bootnodes=n}}class uO extends hk{onNewBlocks=new lk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{newBlocks:e=>this.triggerNewBlocks(e)}})}triggerNewBlocks(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(_e.sequenceVarLen(ms.Codec.View),e,t.genericConfig.chainSpec);this.onNewBlocks.emit(r)}else lO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}announceHeader(e,t){const r=Ae.encodeObject(fs,t);e.sendSignal("announceHeader",r.raw,[r.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive network config!");return this.data}finish(e){return this.onNewBlocks.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class hO extends hk{onNewHeader=new lk;constructor(){super({name:"ready(network)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{announceHeader:e=>this.triggerHeaderAnnouncement(e)}})}triggerHeaderAnnouncement(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(fs,e,t.genericConfig.chainSpec);this.onNewHeader.emit(r)}else lO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}sendBlocks(e,t){const r=this.getConfig(),s=Ae.encodeObject(_e.sequenceVarLen(ms.Codec.View),t,r.genericConfig.chainSpec);e.sendSignal("newBlocks",s.raw,[s.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}class fO{chainSpec;keccakHasher;blocks;states;hashAllocator=new Ke;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:a}=fO.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=a}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=fO.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 Ae.encodeObject(ms.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Tr(e%6),r=new z_(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=bs.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:Or.create({verdicts:[],culprits:[],faults:[]})}),a=Ae.encodeObject(bs.Codec,n,this.chainSpec),o=fe.decodeObject(bs.Codec.View,a,this.chainSpec),c=r.extrinsic(o).hash,l=L.zero(Ne),d=Ae.create({destination:l.raw});d.i32(e),d.i16(t);const u=us.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Ur(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:L.fill(Ne,42*e%256).asOpaque(),seal:l.asOpaque()}),h=Ae.encodeObject(us.Codec,u,this.chainSpec),f=fe.decodeObject(us.Codec.View,h,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,ms.create({header:u,extrinsic:n})}}const gO=Xs.new(void 0,"block-generator");class pO extends hk{onBlock=new lk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):gO.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 bO extends hk{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 mO=Xs.new(void 0,"block-generator");if(!IE.isMainThread){Xs.configureAll(process.env.JAM_LOG??"",Fs.LOG);const e=function(){const e=new pk("ready(generator)",Ct.reInit),t=new bO,r=new fk;return new dk("block-generator",e,[e,t,r])}();ak.receiveChannel(e,IE.parentPort).then(e=>async function(e){mO.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new kE(r.dbPath),i=new wE(r.chainSpec,s),n=new ZC(r.chainSpec,s),a=await t.doUntil("finished",async(e,t,s)=>{let a=0;const o=new fO(r.chainSpec,await ft.create(),i,n);for(;!s();){await(0,Qs.setTimeout)(1e3*r.chainSpec.slotDuration),a+=1;const s=await o.nextEncodedBlock();mO.trace(`Sending block ${a}`),e.sendBlock(t,s)}});mO.info("Block Generator finished. Closing channel."),a.currentState().close(e)}(e)).catch(e=>{mO.error(e),void 0!==e.stack&&mO.error(e.stack),void 0!==e.cause&&mO.error(e.cause)})}const yO=t(import.meta.url)("node:net"),AO=t(import.meta.url)("node:path");class IO{socket;constructor(e){this.socket=e}send(e){!function(e,t){e.write(gS(t)),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}var vO;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(vO||(vO={}));class wO{streamId;type;data;static Codec=_e.Class(wO,{streamId:_e.u32,type:_e.u8.convert(e=>te(e),e=>{switch(e){case vO.Msg:return vO.Msg;case vO.Open:return vO.Open;case vO.Close:return vO.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:_e.blob});static create({streamId:e,type:t,data:r}){return new wO(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class SO{streamByte;static Codec=_e.Class(SO,{streamByte:_e.u8});static create({streamByte:e}){return new SO(e)}constructor(e){this.streamByte=e}}const EO=Xs.new(void 0,"ext-ipc");class CO{sender;streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;constructor(e){this.sender=e;let t=()=>{},r=e=>{};const s=new Promise((e,s)=>{t=e,r=s});this.onEnd={finished:!1,listen:s,resolve:t,reject:r}}registerStreamHandlers(...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 kO(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 kO(i,this.sender);n.open(SO.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=fe.decodeObject(wO.Codec,e),r=t.streamId;EO.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new kO(r,this.sender);if(void 0===s){if(t.type!==vO.Open)return void EO.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=fe.decodeObject(SO.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(EO.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===vO.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===vO.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||EO.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){EO.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 EO.log("Waiting for the handler to be closed."),this.onEnd.listen}}class kO{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Ae.encodeObject(SO.Codec,e);this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Open,data:t})))}bufferAndSend(e){return this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Msg,data:e}))),!0}close(){this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Close,data:P.blobFromNumbers([])})))}}function xO(e,t,r,s,i){return function(n){const a="win32"===lE.platform()?`\\\\.\\pipe\\${n}`:AO.join(lE.tmpdir(),`${n}.ipc`),o=Xs.new(void 0,"ext-ipc"),d=(0,yO.createServer)(n=>{o.log("Client connected");const a=(n=>{const a=new CO(n),o=e=>{if(!(e instanceof c.Announcement))throw new Error(`Invalid annoncement received: ${e}`);a.withStreamOfKind(c.STREAM_KIND,(t,r)=>{t.sendAnnouncement(r,e)})};return t.on(o),a.waitForEnd().finally(()=>{t.off(o)}),a.registerStreamHandlers(new c.Handler(e,r,()=>{},()=>{})),a.registerStreamHandlers(new l.Handler(!0,s,i)),a})(new IO(n));n.on("data",pS(e=>{try{a.onSocketMessage(e)}catch(e){o.error(`Received invalid data on socket: ${e}. Closing connection.`),n.end()}},()=>{o.error("Received too much data on socket. Closing connection."),n.end()})),n.on("end",()=>{o.log("Client disconnected"),a.onClose({})}),n.on("error",e=>{o.error(`Socket error: ${e}`),a.onClose({error:e}),n.end()})});try{oE.unlinkSync(a)}catch{}const u=new AbortController;return d.listen({path:a,signal:u.signal},()=>{o.log(`IPC server is listening at ${a}`)}),d.on("error",e=>{throw e}),()=>{o.info("Closing IPC server."),d.close(),u.abort(),d.unref()}}("typeberry-jamnp")}const _O=Xs.new(void 0,"net");if(!IE.isMainThread){Xs.configureAll(process.env.JAM_LOG??"",Fs.LOG);const e=function(){const e=new pk("ready(network)",dO.reInit),t=new hO,r=new fk;return new dk("network",e,[e,t,r])}();ak.receiveChannel(e,IE.parentPort).then(e=>async function(e){_O.trace(`🛜 Network starting ${e.currentState()}`);const t=await e.waitForState("ready(network)"),r=await t.doUntil("finished",async(e,r)=>{const s=e.getConfig(),i=await Ir(s.key),n=new kE(s.genericConfig.dbPath),a=new wE(s.genericConfig.chainSpec,n);_O.info(`🛜 Listening at ${s.host}:${s.port}`);const o=await async function(e,t,r,s,i,n,a){const o=t.toString().substring(2,10),c=await hS.setup({host:e.host,port:e.port,key:r,protocols:[`jamnp-s/0/${o}`]}),l=new yS(c);l.addPersistentRetry(s);const d=new wS,u=rE.start(i,d,l,n,a);return setImmediate(async()=>{for(;c.isRunning;)await(0,Qs.setTimeout)(3e3),u.maintainSync()}),function(e,t,r){t.peers.onPeerConnected(t=>(t.addOnIncomingStream(e=>(IS(()=>r.onIncomingStream(t,e),r=>{iE.error(`[${t.id}:${e.streamId}]🚰 Stream error: ${r}. Disconnecting peer.`),t.disconnect()}),O)),e.openUp0(t),O))}(u,c,d),{network:c,syncTask:u,streamManager:d}}({host:s.host,port:s.port},s.genesisHeaderHash,i,s.bootnodes.map(nE).filter(e=>e.host!==s.host||e.port!==s.port),s.genericConfig.chainSpec,a,t=>e.sendBlocks(r,t));e.onNewHeader.on(e=>{o.syncTask.broadcastHeader(e)}),t.waitForState("finished").then(()=>o.network.stop()),await o.network.start()});_O.info("🛜 Network worker finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>_O.error(e))}const BO=e=>e.endsWith(".json");function RO(e,t){const r=cE().readFileSync(e),s=P.blobFrom(new Uint8Array(r));return fe.decodeObject(ms.Codec.View,s,t)}function OO(e,t){const r=cE().readFileSync(e,"utf-8"),s=X(JSON.parse(r),(i=t,ee.object({header:Ks,extrinsic:(n=i,ee.object({tickets:Ms,preimages:Ns,guarantees:Us,assurances:kr(n),disputes:ws},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>bs.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>ms.create({header:e,extrinsic:t}))));var i,n;const a=Ae.encodeObject(ms.Codec,s,t);return fe.decodeObject(ms.Codec.View,a,t)}const UO={genesisPath:"",timeSlot:Ur(0),validatorIndex:Tr(0)};class TO{isAuthoring;blocksToImport;nodeName;node;dev;network;static new({isAuthoring:e,blocksToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n,networkConfig:a}){let o=i??{...UO};return void 0!==n&&(o={...o,...n}),new TO(e??!1,t??null,r,s,o,a??null)}constructor(e,t,r,s,i,n){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i,this.network=n}}const NO=Xs.new(void 0,"jam");var DO;async function MO(e,t){if(!IE.isMainThread)return void NO.error("The main binary cannot be running as a Worker!");NO.info(`🎸 Starting node: ${e.nodeName}`);const r=VO(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=ze(e).toString().substring(2,10),n=qe(t).asOpaque(),a=`${r}/${i}/${n.toString().substring(2,10)}`;NO.info(`🛢️ Opening database at ${a}`);try{return{dbPath:a,rootDb:new kE(a,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${a}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new wE(e,r),n=new ZC(e,r),a=i.getBestHeaderHash(),o=i.getPostStateRoot(a);if(NO.log(`🛢️ Best header hash: ${a}`),NO.log(`🛢️ Best state root: ${o}`),null!==o&&!o.isEqualTo(L.zero(Pe))&&!a.isEqualTo(L.zero(Pe)))return void await r.db.close();NO.log("🛢️ Database looks fresh. Initializing.");const c=fe.decodeObject(us.Codec,s.genesisHeader,e),l=ms.create({header:us.empty(),extrinsic:bs.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,d=ms.create({header:c,extrinsic:l}),u=fe.decodeObject(ms.Codec.View,Ae.encodeObject(ms.Codec,d,e),e);NO.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:h,genesisStateRootHash:f}=function(e,t){const r=vt.fromEntries(Array.from(t.entries())),s=QC.fromTruncatedDictionaryUnsafe(r),i=UC.fromStateEntries(e,s),n=s.getRootHash();return NO.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new He(t,u)),await n.insertState(t,h),await i.setPostStateRoot(t,f),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const a=await async function(){const e=oO,t=new nO;return bk(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),o=a.getState("ready(main)").onBestBlock,d=function(e){const t=function(e){const t=function(e){const t=new lk;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=c.HashAndSlot.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit(c.Announcement.create({header:s,final:n}))}),xO(e.chainSpec,t,()=>{const e=r??c.HashAndSlot.create({hash:L.zero(Pe).asOpaque(),slot:Ur(0)});return c.Handshake.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=P.blobFromNumbers([255,255,0,0]);return L.fromBlob(ze("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,Le),Le).isEqualTo(t)&&(r=P.blobFromNumbers([255,255,255,0])),[new l.KeyValuePair(t,r)]})}(e);return()=>{t()}}(e);return()=>{t()}}({chainSpec:r,bestHeader:o}),u=new Ct(r,i,e.node.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,u)),f=LO(h,r,e.blocksToImport),g=await PO(h,e.isAuthoring&&null===e.blocksToImport,u),p=await HO(h,u,n,e.network,null===e.blocksToImport,o);NO.info("[main]⌛ waiting for importer to finish");const b=await f;NO.log("[main] ☠️ Closing the extensions"),d(),NO.log("[main]⌛ waiting for tasks to finish"),await b.currentState().waitForWorkerToFinish(),NO.log("[main] ☠️ Closing the authorship module"),g(),NO.log("[main] ☠️ Closing the networking module"),p(),NO.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(DO||(DO={}));const PO=async(e,t,r)=>{if(!t)return NO.log("✍️ Authorship off: disabled"),()=>Promise.resolve();NO.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=mO,t=new pO;return bk(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"))}}(r);return e.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{NO.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},LO=async(e,t,r)=>null===r?e.waitForState("finished"):(NO.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=BO(r)?OO(r,t):RO(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)NO.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return NO.info("All blocks scheduled to be imported."),e.finish(s)})),HO=async(e,t,r,s,i,n)=>{if(!i||null===s)return NO.log("🛜 Networking off: "+(null===s?"no config":"disabled")),()=>Promise.resolve();const{key:o,host:c,port:l,bootnodes:d}=s,{network:u,finish:h}=await async function(e){const t=(await async function(){return bk(new URL(a(493),a.b),_O,"ready(main)",new uO)}()).transition((t,r)=>t.sendConfig(r,e));return{network:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(dO.new({genericConfig:t,genesisHeaderHash:r,key:o,host:c,port:l,bootnodes:d.map(e=>e.toString())}));return e.doUntil("finished",async(e,t)=>{u.currentState().onNewBlocks.on(r=>{for(const s of r)e.sendBlock(t,s.encoded().raw)})}),u.doUntil("finished",async(e,t)=>{n.on(r=>{e.announceHeader(t,r)})}),h},VO=e=>{if(e===mE.Full)return Et;if(e===mE.Tiny)return St;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[mE.Full,mE.Tiny]}`)},KO=(e=>{var t={};return a.d(t,e),t})({default:()=>s.default}),QO=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] dev <dev-validator-index>\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${bE.name}]\n --config Path to a config file or one of: ['${gE}', '${pE}'].\n [default: ${bE.config}]\n`;var FO;function $O(e,t){const{name:r}=jO(e,"name",e=>e,bE.name),{config:s}=jO(e,"config",e=>e===gE?gE:t(e),bE.config);return{nodeName:r,configPath:s}}function GO(e,t){const r=(0,KO.default)(e),s=r._.shift()??FO.Run;switch(s){case FO.Run:{const e=$O(r,t);return qO(r),{command:FO.Run,args:e}}case FO.Dev:{const e=$O(r,t),s=r._.shift();if(void 0===s)throw new Error("Missing dev-validator index.");const i=Number(s);if(!ie(i))throw new Error(`Invalid dev-validator index: ${i}, need U16`);return qO(r),{command:FO.Dev,args:{...e,index:i}}}case FO.Import:{const e=$O(r,t),s=r._.map(e=>t(e));return r._=[],qO(r),{command:FO.Import,args:{...e,files:s}}}default:r._.unshift(s),qO(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function jO(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 qO(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.Dev="dev",e.Import="import"}(FO||(FO={}));const zO=e=>{const t=e.command===FO.Import?e.args.files:null,r=function(e){if(e===pE)return X(uE,AE.fromJson);if(e===gE)return X(hE,AE.fromJson);try{const t=cE().readFileSync(e,"utf8");return X(JSON.parse(t),AE.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath),s=e.command===FO.Dev?`${e.args.nodeName}-${e.args.index}`:e.args.nodeName,i=e.command===FO.Dev?e.args.index:0,n=function(e,t=new Ke){return qe(P.blobFromParts([Sr.raw,e.raw]),t).asOpaque()}(ze(s).asOpaque());return TO.new({isAuthoring:e.command===FO.Dev,nodeName:s,blocksToImport:t,nodeConfig:r,networkConfig:{key:n,host:"127.0.0.1",port:12345+i,bootnodes:r.chainSpec.bootnodes??[]}})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,d.pathToFileURL)(process.argv[1]).href){Xs.configureAll(process.env.JAM_LOG??"",Fs.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=GO(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(QO),process.exit(1)}MO(zO(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let WO;Xs.configureAll(process.env.JAM_LOG??"",Fs.LOG);try{WO=GO(process.argv.slice(2),JO)}catch(e){console.error(`\n${e}\n`),console.info(QO),process.exit(1)}function JO(e){return e}MO(zO(WO),JO).catch(e=>{console.error(`${e}`),process.exit(-1)});export{FO as Command,QO as HELP,GO as parseArgs,zO 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),a=r(8),o=r(8),c=r(8),l=r(154),d=r(984),u=r(872),h=r(984);class f{getValue(){return this.value}toBinaryString(){return o.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=f;class g extends f{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 g(e)}static fromDecimalDottedString(e){return new g(e)}static fromString(e){return g.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(a.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return g.fromNumber(this.getValue()+1n)}previousIPNumber(){return g.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return b.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[a,o]=i.Validator.isValidIPv4String(e);if(!a)throw new Error(o.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=o.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(a.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=g;class p extends f{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 b extends f{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 b(e)}static fromHexadecatet(e){return new b(e)}static fromString(e){return b.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=o.leftPadWithZeroBit(e,128);return new b(a.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new g(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 b.fromBigInt(this.getValue()+1n)}previousIPNumber(){return b.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${h.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=d.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=b;class m extends g{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 a=e.split(".");this.octets=a.map(e=>s.Octet.fromString(e));let o=n.dottedDecimalNotationToBinaryString(e);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class y extends b{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 a=h.hexadectetNotationToBinaryString(s);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`),this.value=BigInt(`0b${h.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new y(e)}}t.IPv6Mask=y,t.isIPv4=function(e){return 32===e.bitSize}},239:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,a=null;function o(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return o().set(e,r/1),c=e.length,r}let d=null;function u(){return null!==d&&0!==d.byteLength||(d=new Int32Array(n.memory.buffer)),d}function h(e,t){return e>>>=0,o().subarray(e/1,e/1+t)}t.exports.ring_commitment=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.ring_commitment(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.derive_public_key=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.derive_public_key(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.verify_seal=function(e,t,r,s,i){try{const f=n.__wbindgen_add_to_stack_pointer(-16),g=l(e,n.__wbindgen_malloc),p=c,b=l(r,n.__wbindgen_malloc),m=c,y=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(f,g,p,t,b,m,y,A,I,v);var a=u()[f/4+0],o=u()[f/4+1],d=h(a,o).slice();return n.__wbindgen_free(a,1*o,1),d}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.batch_verify_tickets=function(e,t,r){try{const o=n.__wbindgen_add_to_stack_pointer(-16),d=l(e,n.__wbindgen_malloc),f=c,g=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(o,d,f,g,p,r);var s=u()[o/4+0],i=u()[o/4+1],a=h(s,i).slice();return n.__wbindgen_free(s,1*i,1),a}finally{n.__wbindgen_add_to_stack_pointer(16)}};const f=s(928).join(i,"bandersnatch_bg.wasm"),g=s(896).readFileSync(f),p=new WebAssembly.Module(g),b=new WebAssembly.Instance(p,{});n=b.exports,t.exports.__wasm=n},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 a=e[t.charCodeAt(i++)],o=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=a<<2|o>>4,s[n++]=o<<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},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),a=r(660);class o{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 o(e,e)}static fromCidrRange(e){return new o(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]=a.Validator.isValidIPv4String(r),[c]=a.Validator.isValidIPv4String(i),[l]=a.Validator.isValidIPv6String(r),[d]=a.Validator.isValidIPv6String(i);if(n&&c)return new o(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&d)return new o(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 o(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new o(this.getFirst(),e.getLast()):new o(e.getFirst(),this.getLast());if(this.contains(e))return new o(this.getFirst(),this.getLast());if(e.contains(this))return new o(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 o(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new o(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 o(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),a=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new o(i,a)}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 o(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new o(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 d(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=o;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 o(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]=a.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(o),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=a.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 d extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=a.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new d(s.IPv6.fromHexadecatet(o),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 d(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 d(r,t),n=s.getLast().nextIPNumber();return[s,new d(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 d(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 d(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new d(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=d;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),a=e.cidrPrefix.toMask().getValue(),o=n.leftPadWithZeroBit((a^i).toString(2),r);return h(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(o)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(o))};function h(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=h},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},493:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmF3YWl0IHRzSW1wb3J0KCIuL2luZGV4LnRzIiwgaW1wb3J0Lm1ldGEudXJsKTsK"},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),a=r(984),o=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-d(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-d(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=>o.Hexadecatet.fromString(a.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function d(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,a="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),o=64,c=[];e.exports=p;var l=e.exports.BYTES_MIN=16,d=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),h=e.exports.KEYBYTES_MAX=64,f=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),g=e.exports.PERSONALBYTES=16;function p(e,t,r,i,a){if(!(this instanceof p))return new p(e,t,r,i,a);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==a&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=d,"digestLength must be at most "+d+", 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<=h,"key must be at least "+h+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===f,"salt must be exactly "+f+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===g,"personal must be exactly "+g+", was given "+i.length))),c.length||(c.push(o),o+=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,o,o+t.length),this._memory[this.pointer+200]=128)}function b(){}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"),o+e.length>this._memory.length&&this._realloc(o+e.length),this._memory.set(e,o),n.blake2b_update(this.pointer,o,o+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=b),a?a.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,a={};a.__wbindgen_placeholder__=t.exports;let o=null;function c(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let l=0;function d(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=d(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,a,o=(i=s[0],a=s[1],i>>>=0,c().subarray(i/1,i/1+a)).slice();return n.__wbindgen_free(s[0],1*s[1],1),o},t.exports.verify_ed25519_batch=function(e){const t=d(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"),h=s(896).readFileSync(u),f=new WebAssembly.Module(h),g=new WebAssembly.Instance(f,a);n=g.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),a=r(984),o=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=o.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),[a,o]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&a,d=n.concat(o);return l?[l,[]]:[l,d]}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,a.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("/"),a=n[0],o=n[1],l=BigInt(`0b${r(a)}`),d=(l&BigInt(`0b${s(parseInt(o))}`))===l;return d?[d,[]]:[d,[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${o.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${o.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],[a,o]=t(i),[l,d]=t(n),u=a&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let h=o.concat(d);return u?[u,[]]:[u,h]}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 a(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 o(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,o){var c=h[i],l=h[i+1],d=h[o],f=h[o+1];n(u,e,t),a(u,e,c,l);var g=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=g,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=g>>>24^p<<8,u[t+1]=p>>>24^g<<8,n(u,e,t),a(u,e,d,f),g=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=g>>>16^p<<16,u[s+1]=p>>>16^g<<16,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^g<<1,u[t+1]=g>>>31^p<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),d=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),h=new Uint32Array(32);function f(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++)h[r]=o(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,d[16*r+0],d[16*r+1]),c(2,10,18,26,d[16*r+2],d[16*r+3]),c(4,12,20,28,d[16*r+4],d[16*r+5]),c(6,14,22,30,d[16*r+6],d[16*r+7]),c(0,10,20,30,d[16*r+8],d[16*r+9]),c(2,12,22,24,d[16*r+10],d[16*r+11]),c(4,14,16,26,d[16*r+12],d[16*r+13]),c(6,8,18,28,d[16*r+14],d[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var g=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){g.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,g[0]=e,t&&(g[1]=t.length),g[2]=1,g[3]=1,r&&g.set(r,32),s&&g.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^o(g,4*i);t&&(b(this,t),this.c=128)}function b(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,f(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"),b(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;f(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 y=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 y(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],a=i.split(":").filter(e=>""!==e),o=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(a.length+o.length)),l=t(a);""!==l&&(l+=":");let d=t(o);return""!==d&&(d=":"+d),`${l}${c}${d}${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",a="function"==typeof Object.create,o={__proto__:[]}instanceof Array,c=!a&&!o,l={create:a?function(){return Q(Object.create(null))}:o?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]}},d=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,a)},t.prototype.entries=function(){return new r(this._keys,this._values,o)},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 a(e,t){return t}function o(e,t){return[e,t]}}(),h="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}(),f="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@@"+a()}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 a(){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}}(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[g]),C(e)&&(e=function(){var e,r,s,i;C(g)||void 0===t.Reflect||g 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,a=new f,o={isProviderFor:function(e,t){var r=a.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return o}(t.Reflect));var n=new f,a={registerProvider:o,getProvider:l,setProvider:p};return a;function o(t){if(!Object.isExtensible(a))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 h),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 a=M(i);;){var o=L(a);if(!o)return;var c=P(o);if(c.isProviderFor(t,n))return H(a),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 d(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function p(e,t,r){if(!d(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(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),b=function(e){var t=new f,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()),a=0;;){var o=L(n);if(!o)return r.length=a,r;var c=P(o);try{r[a]=c}catch(e){try{H(n)}finally{throw e}}a++}},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 a=t.get(r);C(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}};return p.registerProvider(r),r;function s(s,i,n){var a=t.get(s),o=!1;if(C(a)){if(!n)return;a=new u,t.set(s,a),o=!0}var c=a.get(i);if(C(c)){if(!n)return;if(c=new u,a.set(i,c),!e.setProvider(s,i,r))throw a.delete(i),o&&t.delete(s),new Error("Wrong provider for target.")}return c}}(p);function m(e,t,r){if(y(e,t,r))return!0;var s=V(t);return!k(s)&&m(e,s,r)}function y(e,t,r){var s=K(t,r,!1);return!C(s)&&_(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(y(e,t,r))return I(e,t,r);var s=V(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=K(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){K(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=V(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 h,a=[],o=0,c=r;o<c.length;o++){var l=c[o];n.has(l)||(n.add(l),a.push(l))}for(var d=0,u=i;d<u.length;d++)l=u[d],n.has(l)||(n.add(l),a.push(l));return a}function S(e,t){var r=K(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 V(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===d)return t;if(t!==d)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 K(e,t,r){var s=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.setProvider(e,t,b))return b;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)),y(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=K(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 a,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 a=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,a,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 a{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 a(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 a(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 a(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 a(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,a),r.exports}a.m=i,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.b=new URL("./",import.meta.url);var o={};a.r(o),a.d(o,{Any:()=>Kd,BaseBlock:()=>tl,BaseStringBlock:()=>sl,BitString:()=>td,BmpString:()=>wd,Boolean:()=>Yl,CharacterString:()=>Td,Choice:()=>Qd,Constructed:()=>jl,DATE:()=>Md,DateTime:()=>Ld,Duration:()=>Hd,EndOfContent:()=>zl,Enumerated:()=>od,GeneralString:()=>Ud,GeneralizedTime:()=>Dd,GraphicString:()=>Rd,HexBlock:()=>Wc,IA5String:()=>_d,Integer:()=>ad,Null:()=>Wl,NumericString:()=>Cd,ObjectIdentifier:()=>dd,OctetString:()=>Zl,Primitive:()=>Kl,PrintableString:()=>kd,RawData:()=>$d,RelativeObjectIdentifier:()=>fd,Repeated:()=>Fd,Sequence:()=>gd,Set:()=>pd,TIME:()=>Vd,TeletexString:()=>xd,TimeOfDay:()=>Pd,UTCTime:()=>Nd,UniversalString:()=>Ed,Utf8String:()=>Id,ValueBlock:()=>Yc,VideotexString:()=>Bd,ViewWriter:()=>Rc,VisibleString:()=>Od,compareSchema:()=>Gd,fromBER:()=>Fl,verifySchema:()=>jd});var c={};a.r(c),a.d(c,{Announcement:()=>DS,Handler:()=>PS,Handshake:()=>NS,HashAndSlot:()=>TS,STREAM_KIND:()=>US});var l={};a.r(l),a.d(l,{Handler:()=>WS,KeyValuePair:()=>GS,STREAM_KIND:()=>FS,StateRequest:()=>qS,StateResponse:()=>jS});const d=t(import.meta.url)("node:url");var u,h,f;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(u||(u={}));class g{value;constructor(e){this.value=e}static Less=new g(u.Less);static Greater=new g(u.Greater);static Equal=new g(u.Equal);isLess(){return this.value===u.Less}isGreater(){return this.value===u.Greater}isEqual(){return this.value===u.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}!function(e){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-preview",e.V0_7_1="0.7.1-preview"}(h||(h={})),function(e){e.W3F_DAVXY="w3f-davxy",e.W3F="w3f",e.JAMDUNA="jamduna",e.JAVAJAM="javajam"}(f||(f={}));const p=f.W3F,b=[h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0,h.V0_7_1],m="undefined"==typeof process?{}:process.env,y=h.V0_6_7;let A=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: ${b}`);return t}(m.GP_VERSION),I=m.TEST_SUITE??p;class v{static override(e){A=e}static overrideSuite(e){I=e}static is(...e){return void 0===A?e.includes(y):e.includes(A)}static isSuite(e,t){if(void 0===I)return!1;const r=void 0===t||v.is(t);return e===I&&r}static isGreaterOrEqual(e){const t=b.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${b}`);return v.is(...b.slice(t))}static isLessThan(e){return!v.isGreaterOrEqual(e)}static selectIfGreaterOrEqual({fallback:e,versions:t}){for(const e of b.toReversed()){const r=t[e];if(void 0!==r&&v.isGreaterOrEqual(e))return r}return e}}function w(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function S(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function E(e){throw new Error(`Unexpected value: ${e}`)}function C(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function k(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=>k(e))}]`;if(e instanceof Map)return k(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&&B.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(k(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const x="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 B{toString(){return k(this)}}function _(e){return e}function R(e){return e}const O=Symbol("ok");class U{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}) - ${T(this.error)}`}}const T=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof U?e.toString():`${e.kind} - ${T(e.error)}`:`${e}`;var t};function N(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${T(e.error)}`}const D={ok:e=>(w(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(w(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>D.error(new U(t,r.error,e),r.details)},M=(t(import.meta.url)("node:assert"),Symbol("compare using"));class P{[M](){return this.toString()}raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=j?String.fromCharCode(e+Q-j):String.fromCharCode(e+V);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&&z(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 g.Less;if(r[e]>s[e])return g.Greater}return this.length<e.length?g.Less:this.length>e.length?g.Greater:g.Equal}static empty(){return new P(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return P.blobFrom(t.encode(e))}static blobFrom(e){return new P(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 P(i)}static blobFromNumbers(e){w(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new P(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]=H(t)}return new P(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return P.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield P.blobFrom(this.raw.subarray(t,t+e))}}class L extends P{length;constructor(e,t){super(e),w(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new L(e,t)}static fromNumbers(e,t){w(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new L(r,t)}static zero(e){return new L(new Uint8Array(e),e)}static fill(e,t){w((255&t)===t,"Input has to be a byte.");const r=L.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=P.parseBlobNoPrefix(e);return new L(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=P.parseBlob(e);return new L(r.raw,t)}isEqualTo(e){return w(this.length===e.length,"Comparing incorrectly typed bytes!"),z(this.raw,e.raw)}asOpaque(){return this}}function H(e){return w(2===e.length,"Two-character string expected"),q(e.charCodeAt(0))<<4|q(e.charCodeAt(1))}const V="0".charCodeAt(0),K="9".charCodeAt(0),Q="a".charCodeAt(0),F="f".charCodeAt(0),$="A".charCodeAt(0),G="F".charCodeAt(0),j=10;function q(e){if(e>=V&&e<=K)return e-V;if(e>=Q&&e<=F)return e-Q+j;if(e>=$&&e<=G)return e-$+j;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function z(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const W=(e,t)=>e.compare(t);class J{data;bitLength;static fromBlob(e,t){return new J(e,t)}static fromBytes(e,t){return new J(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new J(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,w(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){w(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){w(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){w(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 Y=Symbol("no key");function X(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]=X(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:X(e,t[1],r);if("object"===s)return Z(t[1],e,r);if("string"===s)return Z(t[1],X(e,s,r),r);if("number"===s){const s=t[0];return Z(t[1],X(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,a=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]=X(t,a[e],`${r}.${e}`)}else Array.isArray(a[e])&&"optional"===a[e][0]&&(i[e]=Y);const o=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 a=[],o=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&a.push(1===t?[o(e),o(void 0)]:[o(void 0),o(e)]);return a}(i,t);if(o.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${o.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===Y&&delete i[e];return i}function Z(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var ee;!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]=X(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,a]of Object.entries(r))i.set(X(n,e,`${s}.key`),X(a,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=X(r,e,s);return t(i)})}}(ee||(ee={}));const te=e=>S(e,re(e),`input must have one-byte representation, got ${e}`),re=e=>(255&e)===e,se=e=>S(e,ie(e),`input must have two-byte representation, got ${e}`),ie=e=>(65535&e)===e,ne=e=>S(e,ae(e),`input must have four-byte representation, got ${e}`),ae=e=>(4294967295&e)>>>0===e,oe=e=>{const t=BigInt(e);return S(t,ce(t),`input must have eight-byte representation, got ${e}`)},ce=e=>(18446744073709551615n&e)===e;function le(...e){let t=0n;for(const r of e)t+=r;const r=!ce(t);return t&=0xffffffffffffffffn,{overflow:r,value:oe(t)}}function de(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function ue(e){return w(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 fe{source;offset;context;static fromBytesBlob(e,t){return new fe(e.raw,t)}static fromBlob(e){return new fe(e)}static decodeObject(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.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 fe(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,L.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=pe(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=pe(e);if(this.offset+=1,0===t)return oe(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return oe(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 oe(r)}bytes(e){if(0===e)return L.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,L.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,P.blobFrom(t)}bitVecFixLen(e){if(0===e)return J.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 J.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):(w(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(w(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 ge=[255,254,252,248,240,224,192,128];function pe(e){w(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<ge.length;t++)if(e>=ge[t])return 8-t;return 0}function be(e){return w(e.isExact,"The value is not exact size estimation!"),e.bytes}function me(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const ye=10485760;class Ae{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new Ae(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(ye,t),{maxByteLength:ye}),s=new Uint8Array(r);return new Ae(s,r)}static encodeObject(e,t,r){const s=Ae.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 P.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;w(e<t,"Only for numbers up to 2**64 - 1"),w(-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(ne(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);w(e<r,`Only for numbers up to 2**${8*t} - 1`),w(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){w(e>=0,"Only for natural numbers."),w(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(ne(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(L.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(ne(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){w(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(ne(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}){w(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 Ie{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=pe(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 ve(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 we{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 Se{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 P.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return P.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];w(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 Ie(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 we(()=>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 S(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class Ee{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=S(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?P.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),P.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){w(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 Ie(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new we(()=>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 S(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Ce{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Ce(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Ce(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 Ie(e));const r=e.bytesRead();return P.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Ce(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 ke(e){return e.convert(e=>(w(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function xe(e){return{bytes:e,isExact:!0}}var Be,_e;function Re(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function Oe(e){return e.View!==e}(_e=Be||(Be={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Ce.new(`Bytes<${t}>`,xe(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),_e.varU32=Ce.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),_e.varU64=Ce.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),_e.u64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),_e.bytes(8)),_e.u32=Ce.withView("u32",xe(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),_e.bytes(4)),_e.u24=Ce.withView("u24",xe(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),_e.bytes(3)),_e.u16=Ce.withView("u16",xe(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),_e.bytes(2)),_e.u8=Ce.new("u8",xe(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),_e.i64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),_e.bytes(8)),_e.i32=Ce.withView("i32",xe(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),_e.bytes(4)),_e.i24=Ce.withView("i24",xe(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),_e.bytes(3)),_e.i16=Ce.withView("i16",xe(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),_e.bytes(2)),_e.i8=Ce.new("i8",xe(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),_e.bool=Ce.new("bool",xe(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),_e.blob=Ce.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),_e.string=Ce.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(P.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),_e.blob),_e.bitVecVarLen=Ce.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),_e.bitVecFixLen=e=>Ce.new(`BitVec[${e}]`,xe(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),_e.optional=e=>{const t=Ce.new(`Optional<${e.name}>`,me({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Oe(e)?Ce.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,_e.optional(e.View)):t},_e.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Ce.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{ve(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return ve(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return ve(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 ve(t,s,i),r.sequenceFixLen(e,s)};return Ce.new(i,r,(e,r)=>{ve(t,r.length,i);const s=r.encoded();e.bytes(L.fromBlob(s.raw,s.length))},t=>{const r=new Ee(t.clone(),e);return n(new Ie(t)),r},n)}(e,t))},_e.sequenceFixLen=(e,t)=>Ce.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 Ce.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},r=>{const i=new Ee(r.clone(),e,t);return s(new Ie(r)),i},s)}(e,{fixedLength:t})),_e.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Ce.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*me(e.sizeHint,t.sizeHint).bytes:32*(me(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const a=Array.from(n.entries());a.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(ne(a.length));for(const[r,s]of a)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,a=s??i.varU32();let o=null;for(let s=0;s<a;s+=1){const s=e.decode(i),a=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==o&&r(o,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${s}"!`);n.set(s,a),o=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return Oe(t)?Ce.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,_e.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},_e.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Ce.new(e,t,r,s,i),_e.select=({name:e,sizeHint:t},r)=>Ce.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),_e.object=(e,t="object",r=e=>e)=>_e.Class({name:t,create:r},e),_e.Class=(e,t)=>{let r=xe(0);Re(t,(e,t)=>{r=me(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Re(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Se{constructor(r){super(r,e,t)}}return Re(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Ce.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new Ie(e)),t},s)}(e,t,r,s);return Ce.withView(e.name,r,(e,r)=>{Re(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Re(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Ue=a(239);const Te=32,Ne=96,De=144,Me=144,Pe=32,Le=31;class He extends B{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ve extends He{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Ke{emptyHash(){return L.zero(Pe)}}const Qe=new Ke;var Fe,$e=a(675),Ge=a.n($e);function je(e,t=Qe){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Ge()(Pe);for(const t of e)s?.update(t instanceof P?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function qe(e,t=Qe){const r=Ge()(Pe),s=e instanceof P?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function ze(e,t=Qe){return qe(P.blobFromString(e),t)}function We(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Je{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 We(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Ye="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Xe=null!==(Fe=Ye.Buffer)&&void 0!==Fe?Fe:null,Ze=Ye.TextEncoder?new Ye.TextEncoder:null;function et(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const tt="a".charCodeAt(0)-10,rt="0".charCodeAt(0);function st(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+tt:r+rt,r=15&t[i],e[s++]=r>9?r+tt:r+rt}return String.fromCharCode.apply(null,e)}const it=null!==Xe?e=>{if("string"==typeof e){const t=Xe.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Xe.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 Ze.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},nt=new Uint8Array(256);for(let e=0;e<64;e++)nt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function at(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=nt[e.charCodeAt(t)],n=nt[e.charCodeAt(t+1)],a=nt[e.charCodeAt(t+2)],o=nt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|a>>2,i+=1,s[i]=(3&a)<<6|63&o,i+=1}return s}const ot=16384,ct=new Je,lt=new Map;function dt(e,t){return We(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),a=ct.dispatch(()=>We(this,void 0,void 0,function*(){if(!lt.has(e.name)){const t=at(e.data),r=WebAssembly.compile(t);lt.set(e.name,r)}const t=yield lt.get(e.name);r=yield WebAssembly.instantiate(t,{})})),o=(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+ot);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(it(e))},l=new Uint8Array(2*t),d=(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):st(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<ot;let h=u;switch(e.name){case"argon2":case"scrypt":h=()=>!0;break;case"blake2b":case"blake2s":h=(e,t)=>t<=512&&u(e);break;case"blake3":h=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":h=()=>!1}return yield(()=>We(this,void 0,void 0,function*(){r||(yield a);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,ot)}))(),{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:o,update:c,digest:d,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),a=r.exports.memory.buffer,o=new Uint8Array(a,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]=et(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(o,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),a=n(),o=4+a,c=r.exports.memory.buffer;if(t.length!==o)throw new Error(`Bad state length (expected ${o} 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]!==et(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,a).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!h(e,i))return o(i),c(e),d("hex",n);const a=it(e);return s.set(a),r.exports.Hash_Calculate(a.length,i,n),st(l,s,t)},hashLength:t}})}new Je,new Je,new DataView(new ArrayBuffer(4)),new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Je,new Je;var ut={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 ht(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Je,new Je;class ft{hasher;static async create(){return new ft(await function(e=512){if(ht(e))return Promise.reject(ht(e));const t=e/8;return dt(ut,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 gt(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return L.fromBlob(e.hasher.digest("binary"),Pe)}class pt{map=new Map;constructor(){}static new(){return new pt}static fromEntries(e){const t=new pt;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 bt{map;static viewDictionaryKeys(e){return new bt(e)}static from(e){const t=bt.new();return t.insertAll(e),t}static new(){return new bt}constructor(e=pt.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 mt(e){return e}class yt extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){w(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new yt(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 yt.new(r,t)}toString(){return k(Array.from(this))}}class At{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new At(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new At([],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 At(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,a=r(t[n],e);if(a.isEqual())return{idx:n,isEqual:!0};a.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){w(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,a=n.length,o=new Array(i+a);let c=0,l=0,d=0;for(;c<i&&l<a;)r(s[c],n[l]).isLess()?o[d++]=s[c++]:(r(s[c],n[l]).isGreater()||(o[d++]=s[c++]),o[d++]=n[l++]);for(;c<i;)o[d++]=s[c++];for(;l<a;)o[d++]=n[l++];return At.fromSortedArray(r,o)}*[Symbol.iterator](){for(const e of this.array)yield e}}class It extends At{static fromArray(e,t=[]){if(0===t.length)return new It([],e);const r=t.toSorted((t,r)=>e(t,r).value),s=r.length,i=[r[0]];for(let t=1;t<s;t++)e(r[t-1],r[t]).isEqual()||i.push(r[t]);return new It(i,e)}static fromArrayUnique(e,t){const r=t.toSorted((t,r)=>e(t,r).value),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 It(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new It([],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 It(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}replace(e){const t=this.binarySearch(e),r=t.isEqual?1:0;this.array.splice(t.idx,r,e)}static fromTwoSortedCollections(e,t){w(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return It.fromSortedArray(r,t.array);if(0===t.length)return It.fromSortedArray(r,e.array);const s=At.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,It.fromSortedArray(r,s)}}class vt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=L.zero(Pe).asOpaque();return r.raw.set(e.raw.subarray(0,Le)),[r,t]});return new vt(pt.fromEntries(t))}truncatedKey=L.zero(Pe).asOpaque();constructor(e){this.dict=e}[M](){return this.dict}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.has(this.truncatedKey)}set(e,t){const r=L.zero(Pe);r.raw.set(e.raw.subarray(0,Le)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}*entries(){for(const[e,t]of this.dict.entries())yield[L.fromBlob(e.raw.subarray(0,Le),Le).asOpaque(),t]}[Symbol.iterator](){return this.entries()}}class wt extends B{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;preimageExpungePeriod;slotDuration;epochLength;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;rotationPeriod;numberECPiecesPerSegment;erasureCodedPieceSize;maxBlockGas;maxRefineGas;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=se(Math.floor(e.validatorsCount/3)),this.validatorsSuperMajority=se(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,this.erasureCodedPieceSize=ne(4104/e.numberECPiecesPerSegment),this.maxBlockGas=e.maxBlockGas,this.maxRefineGas=e.maxRefineGas}}const St=new wt({validatorsCount:se(6),coresCount:se(2),epochLength:ne(12),contestLength:ne(10),maxTicketsPerExtrinsic:te(3),rotationPeriod:se(4),slotDuration:se(6),ticketsPerValidator:te(3),numberECPiecesPerSegment:ne(1026),preimageExpungePeriod:ne(32),maxBlockGas:oe(2e7),maxRefineGas:oe(1e9)}),Et=new wt({validatorsCount:se(1023),coresCount:se(341),epochLength:ne(600),contestLength:ne(500),maxTicketsPerExtrinsic:te(16),rotationPeriod:se(10),slotDuration:se(6),ticketsPerValidator:te(2),numberECPiecesPerSegment:ne(6),preimageExpungePeriod:ne(19200),maxBlockGas:oe(35e8),maxRefineGas:oe(5e9)});class Ct{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new Ct(new wt(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function kt(e){const t=Et,{name:r,sizeHint:s}=e(t),i=new Map;return Be.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof wt){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 xt=(e,t,r)=>"fixedLength"in t?ke(Be.sequenceFixLen(e,t.fixedLength)).convert(R,mt):ke(Be.sequenceVarLen(e,t)).convert(R,mt),Bt=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return Be.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),yt.new(e,t)))},_t=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Ce.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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=pt.new(),n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${n}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class Rt extends B{attempt;signature;static Codec=Be.Class(Rt,{attempt:Be.u8.asOpaque(),signature:Be.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new Rt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Ot extends B{id;attempt;static Codec=Be.Class(Ot,{id:Be.bytes(Pe),attempt:Be.u8.asOpaque()});static create({id:e,attempt:t}){return new Ot(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const Ut=xt(Rt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Tt;!function(e){e.bytesN=e=>ee.fromString(t=>L.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>ee.fromString(t=>L.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>ee.fromString(e=>L.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>ee.fromString(e=>L.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=ee.fromString(P.parseBlob),e.bytesBlobNoPrefix=ee.fromString(P.parseBlobNoPrefix),e.ed25519Signature=ee.fromString(e=>L.parseBytes(e,64).asOpaque()),e.ticketAttempt=ee.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return te(e)}),e.uint8Array=ee.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=ee.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=ee.fromAny(e=>BigInt(e))}(Tt||(Tt={}));const Nt=2n**255n-19n,Dt=2n**252n+27742317777372353535851937790883648493n,Mt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Pt=0x6666666666666666666666666666666666666666666666666666666666666658n,Lt={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Nt,n:Dt,h:8,Gx:Mt,Gy:Pt},Ht=(e="")=>{throw new Error(e)},Vt=e=>"string"==typeof e,Kt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Ht("Uint8Array of valid length expected"):e,Qt=e=>new Uint8Array(e),Ft=(e,t)=>Kt(Vt(e)?Xt(e):Qt(Kt(e)),t),$t=(e,t=Nt)=>{let r=e%t;return r>=0n?r:t+r},Gt=e=>e instanceof jt?e:Ht("Point expected");class jt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new jt(e.x,e.y,1n,$t(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Lt,s=(e=Ft(e,32)).slice(),i=e[31];s[31]=-129&i;const n=er(s);!t||0n<=n&&n<2n**256n||Ht("bad y coord 1"),t||0n<=n&&n<Nt||Ht("bad y coord 2");const a=$t(n*n),o=$t(a-1n),c=$t(r*a+1n);let{isValid:l,value:d}=nr(o,c);l||Ht("bad y coordinate 3");const u=1n==(1n&d),h=!!(128&i);return!t&&0n===d&&h&&Ht("bad y coord 3"),h!==u&&(d=$t(-d)),new jt(d,n,1n,$t(d*n))}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:a}=Gt(e),o=$t(t*a),c=$t(i*s),l=$t(r*a),d=$t(n*s);return o===c&&l===d}is0(){return this.equals(zt)}negate(){return new jt($t(-this.ex),this.ey,this.ez,$t(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Lt,i=$t(e*e),n=$t(t*t),a=$t(2n*$t(r*r)),o=$t(s*i),c=e+t,l=$t($t(c*c)-i-n),d=o+n,u=d-a,h=o-n,f=$t(l*u),g=$t(d*h),p=$t(l*h),b=$t(u*d);return new jt(f,g,b,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:a,ez:o,et:c}=Gt(e),{a:l,d}=Lt,u=$t(t*n),h=$t(r*a),f=$t(i*d*c),g=$t(s*o),p=$t((t+r)*(n+a)-u-h),b=$t(g-f),m=$t(g+f),y=$t(h-l*u),A=$t(p*b),I=$t(m*y),v=$t(p*y),w=$t(b*m);return new jt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Ht("cannot multiply by 0"):zt;if("bigint"==typeof e&&0n<e&&e<Dt||Ht("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(qt))return pr(e).p;let r=zt,s=qt;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(Lt.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Dt/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(zt))return{x:0n,y:1n};const s=rr(r,Nt);return 1n!==$t(r*s)&&Ht("invalid inverse"),{x:$t(e*s),y:$t(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Zt(t);return r[31]|=1n&e?128:0,r}toHex(){return Jt(this.toRawBytes())}}jt.BASE=new jt(Mt,Pt,1n,$t(Mt*Pt)),jt.ZERO=new jt(0n,1n,1n,0n);const{BASE:qt,ZERO:zt}=jt,Wt=(e,t)=>e.toString(16).padStart(t,"0"),Jt=e=>Array.from(Kt(e)).map(e=>Wt(e,2)).join(""),Yt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Xt=e=>{const t="hex invalid";if(!Vt(e))return Ht(t);const r=e.length,s=r/2;if(r%2)return Ht(t);const i=Qt(s);for(let r=0,n=0;r<s;r++,n+=2){const s=Yt(e.charCodeAt(n)),a=Yt(e.charCodeAt(n+1));if(void 0===s||void 0===a)return Ht(t);i[r]=16*s+a}return i},Zt=e=>Xt(Wt(e,64)).reverse(),er=e=>BigInt("0x"+Jt(Qt(Kt(e)).reverse())),tr=(...e)=>{const t=Qt(e.reduce((e,t)=>e+Kt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},rr=(e,t)=>{(0n===e||t<=0n)&&Ht("no inverse n="+e+" mod="+t);let r=$t(e,t),s=t,i=0n,n=1n,a=1n,o=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-a*e,l=n-o*e;s=r,r=t,i=a,n=o,a=c,o=l}return 1n===s?$t(i,t):Ht("no inverse")},sr=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Nt;return r},ir=19681161376707505956807079304988542015446066515923890162744021073123829784752n,nr=(e,t)=>{const r=$t(t*t*t),s=(e=>{const t=e*e%Nt*e%Nt,r=sr(t,2n)*t%Nt,s=sr(r,1n)*e%Nt,i=sr(s,5n)*s%Nt,n=sr(i,10n)*i%Nt,a=sr(n,20n)*n%Nt,o=sr(a,40n)*a%Nt,c=sr(o,80n)*o%Nt,l=sr(c,80n)*o%Nt,d=sr(l,10n)*i%Nt;return{pow_p_5_8:sr(d,2n)*e%Nt,b2:t}})(e*$t(r*r*t)).pow_p_5_8;let i=$t(e*r*s);const n=$t(t*i*i),a=i,o=$t(i*ir),c=n===e,l=n===$t(-e),d=n===$t(-e*ir);return c&&(i=a),(l||d)&&(i=o),1n==(1n&$t(i))&&(i=$t(-i)),{isValid:c||l,value:i}},ar=e=>$t(er(e),Dt);let or;const cr=(...e)=>fr.sha512Async(...e),lr=e=>{const t=e.slice(0,32);t[0]&=248,t[31]&=127,t[31]|=64;const r=e.slice(32,64),s=ar(t),i=qt.mul(s),n=i.toRawBytes();return{head:t,prefix:r,scalar:s,point:i,pointBytes:n}},dr=e=>cr(Ft(e,32)).then(lr);function ur(e,t){return e?cr(t.hashable).then(t.finish):t.finish(((...e)=>"function"==typeof or?or(...e):Ht("etc.sha512Sync not set"))(t.hashable))}const hr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,fr={bytesToHex:Jt,hexToBytes:Xt,concatBytes:tr,mod:$t,invert:rr,randomBytes:(e=32)=>{const t=hr();return t&&t.getRandomValues||Ht("crypto.getRandomValues must be defined"),t.getRandomValues(Qt(e))},sha512Async:async(...e)=>{const t=hr(),r=t&&t.subtle;r||Ht("etc.sha512Async or crypto.subtle must be defined");const s=tr(...e);return Qt(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let gr;Object.defineProperties(fr,{sha512Sync:{configurable:!1,get:()=>or,set(e){or||(or=e)}}});const pr=e=>{const t=gr||(gr=(()=>{const e=[];let t=qt,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=zt,i=qt;const n=BigInt(255),a=BigInt(8);for(let o=0;o<33;o++){const c=128*o;let l=Number(e&n);e>>=a,l>128&&(l-=256,e+=1n);const d=c,u=c+Math.abs(l)-1,h=o%2!=0,f=l<0;0===l?i=i.add(r(h,t[d])):s=s.add(r(f,t[u]))}return{p:s,f:i}};var br=a(625);const mr=32,yr=64;class Ar{pubKey;_privKey;constructor(e,t){this.pubKey=e,this._privKey=t}}async function Ir(e){const t=await(r=e.raw,dr(r).then(e=>e.pointBytes));var r;return new Ar(L.fromBlob(t,mr).asOpaque(),e.asOpaque())}async function vr(e,t){const r=await(async(e,t)=>{const r=Ft(e),s=await dr(t);return ur(!0,((e,t,r)=>{const{pointBytes:s,scalar:i}=e,n=ar(t),a=qt.mul(n).toRawBytes();return{hashable:tr(a,s,r),finish:e=>{const t=$t(n+ar(e)*i,Dt);return Kt(tr(a,Zt(t)),64)}}})(s,await cr(s.prefix,r),r))})(t.raw,e._privKey.raw);return L.fromBlob(r,yr).asOpaque()}async function wr(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+=mr,r.set(n.raw,s),s+=yr;const e=i.length;w(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,br.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}const Sr=L.blobFromString("jam_val_key_ed25519");L.blobFromString("jam_val_key_bandersnatch");class Er extends B{anchor;bitfield;validatorIndex;signature;static Codec=Be.Class(Er,{anchor:Be.bytes(Pe).asOpaque(),bitfield:kt(e=>Be.bitVecFixLen(e.coresCount)),validatorIndex:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new Er(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const Cr=kt(e=>xt(Er.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),kr=e=>ee.array((e=>ee.object({anchor:Tt.bytes32(),bitfield:ee.fromString(t=>{const r=Math.ceil(e.coresCount/8);return J.fromBytes(L.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Tt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>Er.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class xr extends B{workReportHash;wasConsideredValid;key;signature;static Codec=Be.Class(xr,{workReportHash:Be.bytes(Pe).asOpaque(),wasConsideredValid:Be.bool,key:Be.bytes(mr).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new xr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class Br extends B{workReportHash;key;signature;static Codec=Be.Class(Br,{workReportHash:Be.bytes(Pe).asOpaque(),key:Be.bytes(mr).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new Br(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class _r extends B{isWorkReportValid;index;signature;static Codec=Be.Class(_r,{isWorkReportValid:Be.bool,index:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new _r(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class Rr extends B{workReportHash;votesEpoch;votes;static Codec=Be.Class(Rr,{workReportHash:Be.bytes(Pe).asOpaque(),votesEpoch:Be.u32.asOpaque(),votes:kt(e=>ke(Be.sequenceFixLen(_r.Codec,e.validatorsSuperMajority)).convert(R,mt))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new Rr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class Or extends B{verdicts;culprits;faults;static Codec=Be.Class(Or,{verdicts:Be.sequenceVarLen(Rr.Codec),culprits:Be.sequenceVarLen(Br.Codec),faults:Be.sequenceVarLen(xr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new Or(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Ur=e=>ne(e),Tr=e=>se(e),Nr=e=>ne(e),Dr=e=>oe(e),Mr=e=>se(e),Pr=e=>ne(e);function Lr(e,t){return w(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Hr=e=>kt(t=>xt(e,{fixedLength:t.validatorsCount}));function Vr(e,t){return w(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Kr=e=>kt(t=>xt(e,{fixedLength:t.epochLength}));class Qr extends B{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=Be.Class(Qr,{anchor:Be.bytes(Pe).asOpaque(),stateRoot:Be.bytes(Pe).asOpaque(),beefyRoot:Be.bytes(Pe).asOpaque(),lookupAnchor:Be.bytes(Pe).asOpaque(),lookupAnchorSlot:Be.u32.asOpaque(),prerequisites:Be.sequenceVarLen(Be.bytes(Pe).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Qr(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 Fr extends B{treeRoot;index;static Codec=Be.Class(Fr,{treeRoot:Be.bytes(Pe),index:Be.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Fr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class $r extends B{hash;len;static Codec=Be.Class($r,{hash:Be.bytes(Pe).asOpaque(),len:Be.u32});static create({hash:e,len:t}){return new $r(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class Gr extends B{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=Be.Class(Gr,{service:Be.u32.asOpaque(),codeHash:Be.bytes(Pe).asOpaque(),payload:Be.blob,refineGasLimit:Be.u64.asOpaque(),accumulateGasLimit:Be.u64.asOpaque(),importSegments:xt(Fr.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:Be.sequenceVarLen($r.Codec),exportCount:Be.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:a,exportCount:o}){return new Gr(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=a,this.exportCount=o}}function jr(e){return S(e,e>=qr&&e<=zr,`WorkItemsCount: Expected '${qr} <= count <= ${zr}' got ${e}`)}const qr=1,zr=16;class Wr extends B{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=Be.Class(Wr,{authorization:Be.blob,authCodeHost:Be.u32.asOpaque(),authCodeHash:Be.bytes(Pe).asOpaque(),parametrization:Be.blob,context:Qr.Codec,items:Be.sequenceVarLen(Gr.Codec).convert(e=>e,e=>yt.new(e,jr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Wr(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 Jr,Yr;(Yr=Jr||(Jr={}))[Yr.ok=0]="ok",Yr[Yr.outOfGas=1]="outOfGas",Yr[Yr.panic=2]="panic",Yr[Yr.badCode=3]="badCode",Yr[Yr.codeOversize=4]="codeOversize";class Xr extends B{kind;okBlob;static Codec=Be.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===Jr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Jr.ok){const r=e.bytesBlob();return new Xr(t,r)}if(t>Jr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Xr(t)},e=>{e.decoder.varU32()===Jr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Zr extends B{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=Be.Class(Zr,{gasUsed:Be.varU64.asOpaque(),importedSegments:Be.varU32,extrinsicCount:Be.varU32,extrinsicSize:Be.varU32,exportedSegments:Be.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Zr(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 es{serviceId;codeHash;payloadHash;gas;result;load;static Codec=Be.Class(es,{serviceId:Be.u32.asOpaque(),codeHash:Be.bytes(Pe).asOpaque(),payloadHash:Be.bytes(Pe),gas:Be.u64.asOpaque(),result:Xr.Codec,load:Zr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new es(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 ts extends B{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=Be.Class(ts,{hash:Be.bytes(Pe).asOpaque(),length:Be.u32,erasureRoot:Be.bytes(Pe),exportsRoot:Be.bytes(Pe).asOpaque(),exportsCount:Be.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new ts(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 rs extends B{workPackageHash;segmentTreeRoot;static Codec=Be.Class(rs,{workPackageHash:Be.bytes(Pe).asOpaque(),segmentTreeRoot:Be.bytes(Pe).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new rs(e,t)}}class ss extends B{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=Be.Class(ss,{workPackageSpec:ts.Codec,context:Qr.Codec,coreIndex:v.isGreaterOrEqual(h.V0_6_5)&&!v.isSuite(f.JAMDUNA,h.V0_6_5)?Be.varU32.convert(e=>ne(e),e=>{if(!ie(e))throw new Error(`Core index exceeds U16: ${e}`);return Mr(e)}):Be.u16.asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),authorizationOutput:Be.blob,segmentRootLookup:ke(Be.sequenceVarLen(rs.Codec)),results:Be.sequenceVarLen(es.Codec).convert(e=>e,e=>yt.new(e,jr(e.length))),authorizationGasUsed:Be.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:a,authorizationGasUsed:o}){return new ss(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=a,this.authorizationGasUsed=o}}const is=[2,3];class ns extends B{validatorIndex;signature;static Codec=Be.Class(ns,{validatorIndex:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({validatorIndex:e,signature:t}){return new ns(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class as extends B{report;slot;credentials;static Codec=Be.Class(as,{report:ss.Codec,slot:Be.u32.asOpaque(),credentials:xt(ns.Codec,{minLength:is[0],maxLength:is[1],typicalLength:is[1]})});static create({report:e,slot:t,credentials:r}){return new as(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const os=kt(e=>xt(as.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class cs extends B{bandersnatch;ed25519;static Codec=Be.Class(cs,{bandersnatch:Be.bytes(Te).asOpaque(),ed25519:Be.bytes(mr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new cs(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class ls extends B{entropy;ticketsEntropy;validators;static Codec=Be.Class(ls,{entropy:Be.bytes(Pe).asOpaque(),ticketsEntropy:Be.bytes(Pe).asOpaque(),validators:Hr(cs.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new ls(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const ds=e=>{const t=e.encoded().raw,r=t.length-Ne;return P.blobFrom(t.subarray(0,r))},us={parentHeaderHash:Be.bytes(Pe).asOpaque(),priorStateRoot:Be.bytes(Pe).asOpaque(),extrinsicHash:Be.bytes(Pe).asOpaque(),timeSlotIndex:Be.u32.asOpaque(),epochMarker:Be.optional(ls.Codec),ticketsMarker:Be.optional(Kr(Ot.Codec)),offendersMarker:Be.sequenceVarLen(Be.bytes(mr).asOpaque()),bandersnatchBlockAuthorIndex:Be.u16.asOpaque(),entropySource:Be.bytes(Ne).asOpaque(),seal:Be.bytes(Ne).asOpaque()};class hs extends B{static Codec=Be.Class(hs,v.isLessThan(h.V0_7_0)?us:{parentHeaderHash:Be.bytes(Pe).asOpaque(),priorStateRoot:Be.bytes(Pe).asOpaque(),extrinsicHash:Be.bytes(Pe).asOpaque(),timeSlotIndex:Be.u32.asOpaque(),epochMarker:Be.optional(ls.Codec),ticketsMarker:Be.optional(Kr(Ot.Codec)),bandersnatchBlockAuthorIndex:Be.u16.asOpaque(),entropySource:Be.bytes(Ne).asOpaque(),offendersMarker:Be.sequenceVarLen(Be.bytes(mr).asOpaque()),seal:Be.bytes(Ne).asOpaque()});static create(e){return Object.assign(hs.empty(),e)}parentHeaderHash=L.zero(Pe).asOpaque();priorStateRoot=L.zero(Pe).asOpaque();extrinsicHash=L.zero(Pe).asOpaque();timeSlotIndex=Ur(0);epochMarker=null;ticketsMarker=null;bandersnatchBlockAuthorIndex=Tr(0);entropySource=L.zero(Ne).asOpaque();offendersMarker=[];seal=L.zero(Ne).asOpaque();constructor(){super()}static empty(){return new hs}}class fs extends He{static Codec=Be.Class(fs,{hash:Be.bytes(Pe).asOpaque(),data:hs.Codec.View});static create({hash:e,data:t}){return new He(e,t)}}const gs=fs.Codec;class ps extends B{requester;blob;static Codec=Be.Class(ps,{requester:Be.u32.asOpaque(),blob:Be.blob});static create({requester:e,blob:t}){return new ps(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const bs=Be.sequenceVarLen(ps.Codec);class ms extends B{tickets;preimages;guarantees;assurances;disputes;static Codec=Be.Class(ms,{tickets:Ut,preimages:bs,guarantees:os,assurances:Cr,disputes:Or.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new ms(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 ys extends B{header;extrinsic;static Codec=Be.Class(ys,{header:hs.Codec,extrinsic:ms.Codec});static create({header:e,extrinsic:t}){return new ys(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const As=ee.object({target:Tt.bytes32(),vote:"boolean",key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>xr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),Is=ee.object({target:Tt.bytes32(),key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,key:t,signature:r})=>Br.create({workReportHash:e,key:t,signature:r})),vs=ee.object({vote:"boolean",index:"number",signature:Tt.ed25519Signature},({vote:e,index:t,signature:r})=>_r.create({isWorkReportValid:e,index:t,signature:r})),ws=ee.object({target:Tt.bytes32(),age:"number",votes:ee.array(vs)},({target:e,age:t,votes:r})=>Rr.create({workReportHash:e,votesEpoch:t,votes:r})),Ss=ee.object({verdicts:ee.array(ws),culprits:ee.array(Is),faults:ee.array(As)},({verdicts:e,culprits:t,faults:r})=>Or.create({verdicts:e,culprits:t,faults:r})),Es=ee.object({anchor:Tt.bytes32(),state_root:Tt.bytes32(),beefy_root:Tt.bytes32(),lookup_anchor:Tt.bytes32(),lookup_anchor_slot:"number",prerequisites:ee.array(Tt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Qr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),Cs=ee.object({ok:ee.optional(ee.fromString(P.parseBlob)),out_of_gas:ee.optional(ee.fromAny(()=>null)),panic:ee.optional(ee.fromAny(()=>null)),bad_code:ee.optional(ee.fromAny(()=>null)),code_oversize:ee.optional(ee.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 Xr(ne(Jr.ok),t);if(null===r)return new Xr(ne(Jr.outOfGas));if(null===s)return new Xr(ne(Jr.panic));if(null===i)return new Xr(ne(Jr.badCode));if(null===n)return new Xr(ne(Jr.codeOversize));throw new Error("Invalid WorkExecResult")}),ks=ee.object({gas_used:ee.fromNumber(e=>Dr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Zr.create({gasUsed:Dr(e),importedSegments:ne(t),extrinsicCount:ne(r),extrinsicSize:ne(s),exportedSegments:ne(i)})),xs=ee.object({service_id:"number",code_hash:Tt.bytes32(),payload_hash:Tt.bytes32(),accumulate_gas:ee.fromNumber(e=>Dr(e)),result:Cs,refine_load:ks},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>es.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),Bs=ee.object({hash:Tt.bytes32(),length:"number",erasure_root:Tt.bytes32(),exports_root:Tt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>ts.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),_s=ee.object({work_package_hash:Tt.bytes32(),segment_tree_root:Tt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>rs.create({workPackageHash:e,segmentTreeRoot:t})),Rs=ee.object({package_spec:Bs,context:Es,core_index:"number",authorizer_hash:Tt.bytes32(),auth_output:ee.fromString(P.parseBlob),segment_root_lookup:ee.array(_s),results:ee.array(xs),auth_gas_used:ee.fromNumber(e=>Dr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:a,auth_gas_used:o})=>{const c=yt.new(n,jr(n.length));return ss.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:a,results:c,authorizationGasUsed:o})}),Os=ee.object({validator_index:"number",signature:Tt.ed25519Signature},({validator_index:e,signature:t})=>ns.create({validatorIndex:e,signature:t})),Us=ee.object({report:Rs,slot:"number",signatures:ee.array(Os)},({report:e,slot:t,signatures:r})=>as.create({report:e,slot:t,credentials:r})),Ts=ee.array(Us),Ns=ee.object({requester:"number",blob:ee.fromString(P.parseBlob)},({requester:e,blob:t})=>ps.create({requester:e,blob:t})),Ds=ee.array(Ns),Ms=ee.object({attempt:Tt.ticketAttempt,signature:ee.fromString(e=>L.parseBytes(e,784).asOpaque())},e=>Rt.create({attempt:e.attempt,signature:e.signature})),Ps=ee.array(Ms),Ls=ee.fromString(e=>L.parseBytes(e,96).asOpaque()),Hs=ee.object({bandersnatch:Tt.bytes32(),ed25519:Tt.bytes32()},cs.create),Vs=ee.object({entropy:Tt.bytes32(),tickets_entropy:Tt.bytes32(),validators:ee.array(Hs)},e=>ls.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),Ks=ee.object({id:Tt.bytes32(),attempt:Tt.ticketAttempt},e=>Ot.create({id:e.id,attempt:e.attempt})),Qs=ee.object({parent:Tt.bytes32(),parent_state_root:Tt.bytes32(),extrinsic_hash:Tt.bytes32(),slot:"number",epoch_mark:ee.optional(Vs),tickets_mark:ee.optional(ee.array(Ks)),offenders_mark:ee.array(Tt.bytes32()),author_index:"number",entropy_source:Ls,seal:Ls},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:a,author_index:o,entropy_source:c,seal:l})=>{const d=hs.empty();return d.parentHeaderHash=e,d.priorStateRoot=t,d.extrinsicHash=r,d.timeSlotIndex=s,d.epochMarker=i??null,d.ticketsMarker=n??null,d.offendersMarker=a,d.bandersnatchBlockAuthorIndex=o,d.entropySource=c,d.seal=l,d}),Fs=t(import.meta.url)("node:timers/promises");var $s;function Gs(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)}}function js(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===$s[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return $s[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"}($s||($s={}));class qs{options;static create(e,t){return e===$s.TRACE?new zs(t):e===$s.LOG?new Ws(t):e===$s.INFO?new Js(t):new qs(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push($s.WARN,e,t,r)}error(e,t,r){this.push($s.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),a=Gs(this.options,t),o=$s[e].padEnd(5);if(e<a)return;const c=`${o} [${n}] ${s}\n\t@ ${i}`;e===$s.WARN?console.warn(c):e===$s.ERROR?console.error(c):console.info(c)}}class zs extends qs{trace(e,t,r){this.push($s.TRACE,e,t,r)}log(e,t,r){this.push($s.LOG,e,t,r)}info(e,t,r){this.push($s.INFO,e,t,r)}}class Ws extends qs{trace(e,t,r){}log(e,t,r){this.push($s.LOG,e,t,r)}info(e,t,r){this.push($s.INFO,e,t,r)}}class Js extends qs{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push($s.INFO,e,t,r)}}const Ys={workingDir:"",defaultLevel:$s.LOG,modules:new Map},Xs={options:Ys,transport:qs.create(Ys.defaultLevel,Ys)};class Zs{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new Zs(t??r,r,Xs)}static getLevel(e){return Gs(Xs.options,e)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=qs.create(t,e);Xs.options=e,Xs.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(),js(r.trim()))}else n=js(t)}const a="".split("/");return a.pop(),a.pop(),{defaultLevel:n,modules:s,workingDir:r??a.join("/")}}(e,t,r);Zs.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)}}var ei;!function(e){e[e.NOTSET=0]="NOTSET",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=100]="SILENT"}(ei||(ei={}));const ti="captureStackTrace"in Error,ri="stackTraceLimit"in Error;function si(e){switch(e){case ei.NOTSET:return"NOTSET";case ei.DEBUG:return"DEBUG";case ei.INFO:return"INFO";case ei.WARN:return"WARN";case ei.ERROR:return"ERROR";case ei.SILENT:return"SILENT"}}function ii(e,t){return"function"==typeof t?t():t}function ni(e){return JSON.stringify(e,ii)}const ai=Symbol("level"),oi=Symbol("key"),ci=Symbol("keys"),li=Symbol("date"),di=Symbol("msg"),ui=Symbol("stack"),hi=Symbol("data");function fi(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===oi)s+=r.key;else if(n===ci)s+=r.keys;else if(n===li)s+=r.date().toISOString();else if(n===di)null!=r.msg&&(s+=r.msg);else if(n===ai)s+=si(r.level);else if(n===hi)s+=ni(r.data);else if(n===ui){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}}const gi=fi`${ai}:${oi}:${di}`,pi=class{formatter;constructor(e=gi){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)}},bi=class extends pi{emit(e){console.error(e)}};class mi{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=ei.NOTSET,r=[new bi],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 mi(e,ei.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!==ei.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,{},ei.DEBUG,t):this.log(e,t,ei.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ei.INFO,t):this.log(e,t,ei.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ei.WARN,t):this.log(e,t,ei.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ei.ERROR,t):this.log(e,t,ei.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(ti&&ri){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,mi.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 yi=mi,Ai=t(import.meta.url)("node:process"),Ii=class extends pi{emit(e){Ai.stderr.write(e+"\n")}},vi=t(import.meta.url)("dgram");class wi 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 Si=wi;class Ei extends Si{constructor(e){super(Ei.name,e,arguments)}}const Ci=Ei;class ki extends Si{constructor(e){super(ki.name,e,arguments)}}const xi=ki;class Bi extends Si{constructor(e){super(Bi.name,e,arguments)}}const _i=Bi,Ri=Symbol("_eventTarget"),Oi=Symbol("eventTarget"),Ui=Symbol("_eventHandlers"),Ti=Symbol("eventHandlers"),Ni=Symbol("_eventHandled"),Di=Symbol("eventHandled"),Mi=Symbol("_handleEventError"),Pi=Symbol("handleEventError");function Li(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function Hi(e,t){return e.capture===t.capture}function Vi(){return e=>{const t=class extends e{[Ri]=new EventTarget;[Ui]=new Map;[Ni]=new WeakSet;[Mi]=e=>{throw e.detail};constructor(...e){super(...e),this[Ri].addEventListener(_i.name,this[Mi])}get[Oi](){return this[Ri]}get[Ti](){return this[Ui]}get[Di](){return this[Ni]}get[Pi](){return this[Mi]}addEventListener(e,t,r){r=Li(r);const s=this;let i,n,a=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[Ui].get(e),void 0===n&&(n=new Set,this[Ui].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,Hi(e.options,r))){a=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[Ni].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new _i({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new _i({detail:e}))}},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[Ni].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new _i({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new _i({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):i=t,this[Ri].addEventListener(e,i,r),e===_i.name&&1===n?.size&&this[Ri].removeEventListener(_i.name,this[Mi])}removeEventListener(e,t,r){let s,i,n;if(r=Li(r),null!=t){if(i=this[Ui].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&Hi(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[Ri].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===_i.name&&0===i.size&&this[Ri].addEventListener(_i.name,this[Mi]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof _i)return this[Ri].dispatchEvent(e);{let t=this[Ri].dispatchEvent(e);if(t&&!this[Ni].has(e)){const r=new Ci({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[Ri].dispatchEvent(r)}if(t){const r=new xi({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[Ri].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function Ki(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*Qi(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 Fi extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof Fi?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 a=super.then(i,n),o=Fi.from(a,r);return s=o.abortController.signal,o}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 $i=Fi,Gi=t(import.meta.url)("node:perf_hooks");var ji,qi=(ji=function(e,t){return ji=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])},ji(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}ji(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),zi=function(e){function t(t){var r,s,i,n=this.constructor,a=e.call(this,t)||this;return Object.defineProperty(a,"name",{value:n.name,enumerable:!1,configurable:!0}),r=a,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)}(a),a}return qi(t,e),t}(Error);const Wi=class extends zi{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(Gi.performance.timeOrigin+Gi.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 Ji(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=Ji(s,t,r);if(e)return e}return Ji(e.cause,t,r)}return e instanceof Error&&Ji(e.cause,t,r)}class Yi extends Wi{static description="Timer error"}class Xi extends Yi{static description="The timer has already ended"}class Zi{_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 $i((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(Gi.performance.timeOrigin+Gi.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(Gi.performance.timeOrigin+Gi.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()-(Gi.performance.timeOrigin+Gi.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 Xi;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Xi;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(Gi.performance.timeOrigin+Gi.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 en=Zi;function tn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function rn(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new en(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof en&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new en(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new $i((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}class sn extends Wi{static description="Async locks error"}class nn extends sn{static description="Async locks timeout"}const an=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}:{},()=>rn((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=tn();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 a=!1;const o={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{a||(a=!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,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,nn,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}:{},rn((e,t)=>{const{p:r,resolveP:s,rejectP:i}=tn();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)},a={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,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,nn,r,[t])}withF(...e){const t=e.pop();return Ki([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Qi([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()}}},on=class{semaphore=new an(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 Ki([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Qi([this.lock(...e)],([e])=>t(e))}},cn=class{readersLock=new on;writersLock=new on;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}:{},()=>rn(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,nn,e,[])}write(e){return e=null!=e?{...e}:{},()=>rn(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,nn,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return $i.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 Ki([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return Ki([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 Qi([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return Qi([this.write(...e)],([e])=>t(e))}},ln=Symbol("_running"),dn=Symbol("running"),un=Symbol("_destroyed"),hn=Symbol("destroyed"),fn=Symbol("_status"),gn=Symbol("status"),pn=Symbol("_statusP"),bn=Symbol("statusP"),mn=Symbol("resolveStatusP"),yn=Symbol("initLock"),An=(async()=>{}).constructor,In=function*(){}.constructor,vn=async function*(){}.constructor,wn="captureStackTrace"in Error;function Sn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function En(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);wn?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Cn extends Si{}class kn extends Cn{}class xn extends Cn{}class Bn extends Cn{}class _n extends Cn{}class Rn extends Cn{}class On extends Cn{}class Un extends Wi{static description="Async init error"}class Tn extends Un{static description="Async init is not running"}class Nn extends Un{static description="Async init is destroyed"}function Dn({eventDestroy:e=Rn,eventDestroyed:t=On}={}){return r=>{const{p:s,resolveP:i}=Sn(),n=class extends(Vi()(r)){[un]=!1;[fn]=null;[pn]=s;[mn]=i;[yn]=new cn;get[hn](){return this[un]}get[gn](){return this[fn]}get[bn](){return this[pn]}async destroy(...r){return this[yn].withWriteF(async()=>{if(this[un])return;this[fn]="destroying",this[mn]("destroying");const{p:s,resolveP:i}=Sn();let n;return this[pn]=s,this[mn]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[un]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[fn]=null,this[mn](null);const{p:e,resolveP:t}=Sn();this[pn]=e,this[mn]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function Mn(e=new Nn,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof An?async function(...s){if(this[yn].isLocked("write")&&null===this[fn]&&await this[pn],r.includes(this[fn]))return o.apply(this,s);if(t)return this[yn].withReadF(async()=>{if(this[un])throw En(e,n[a]),e;return o.apply(this,s)});if(this[yn].isLocked("write")||this[un])throw En(e,n[a]),e;return o.apply(this,s)}:o instanceof In?function*(...t){if(r.includes(this[fn]))return yield*o.apply(this,t);if(this[yn].isLocked("write")&&null!==this[gn]||this[un])throw En(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof vn?async function*(...s){if(this[yn].isLocked("write")&&null===this[fn]&&await this[pn],r.includes(this[fn]))return yield*o.apply(this,s);if(t)return yield*this[yn].withReadG(()=>{if(this[un])throw En(e,n[a]),e;return o.apply(this,s)});if(this[yn].isLocked("write")||this[un])throw En(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[fn]))return o.apply(this,t);if(this[yn].isLocked("write")&&null!==this[gn]||this[un])throw En(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}function Pn({eventStart:e=kn,eventStarted:t=xn,eventStop:r=Bn,eventStopped:s=_n}={}){return i=>{const{p:n,resolveP:a}=Sn(),o=class extends(Vi()(i)){[ln]=!1;[fn]=null;[pn]=n;[mn]=a;[yn]=new cn;get[dn](){return this[ln]}get[gn](){return this[fn]}get[bn](){return this[pn]}async start(...r){return this[yn].withWriteF(async()=>{if(this[ln])return;this[fn]="starting",this[mn]("starting");const{p:s,resolveP:i}=Sn();let n;return this[pn]=s,this[mn]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[ln]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[fn]=null,this[mn](null);const{p:e,resolveP:t}=Sn();this[pn]=e,this[mn]=t})}async stop(...e){return this[yn].withWriteF(async()=>{if(!this[ln])return;this[fn]="stopping",this[mn]("stopping");const{p:t,resolveP:i}=Sn();let n;return this[pn]=t,this[mn]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[ln]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[fn]=null,this[mn](null);const{p:e,resolveP:t}=Sn();this[pn]=e,this[mn]=t})}};return Object.defineProperty(o,"name",Object.getOwnPropertyDescriptor(i,"name")),o}}function Ln(e=new Tn,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof An?async function(...s){if(this[yn].isLocked("write")&&null===this[fn]&&await this[pn],r.includes(this[fn]))return o.apply(this,s);if(t)return this[yn].withReadF(async()=>{if(!this[ln])throw En(e,n[a]),e;return o.apply(this,s)});if(this[yn].isLocked("write")||!this[ln])throw En(e,n[a]),e;return o.apply(this,s)}:o instanceof In?function*(...t){if(r.includes(this[fn]))return yield*o.apply(this,t);if(this[yn].isLocked("write")&&null!==this[gn]||!this[ln])throw En(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof vn?async function*(...s){if(this[yn].isLocked("write")&&null===this[fn]&&await this[pn],r.includes(this[fn]))return yield*o.apply(this,s);if(t)return yield*this[yn].withReadG(()=>{if(!this[ln])throw En(e,n[a]),e;return o.apply(this,s)});if(this[yn].isLocked("write")||!this[ln])throw En(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[fn]))return o.apply(this,t);if(this[yn].isLocked("write")&&null!==this[gn]||!this[ln])throw En(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}class Hn 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 Vn=Hn;class Kn{[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,Vn.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,Vn.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:[Vn.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[Vn.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 Qn=Kn,Fn="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",$n=t(import.meta.url)("dns"),Gn=t(import.meta.url)("node:events");var jn=a.n(Gn),qn=a(618);class zn extends Wi{static description="QUIC error"}class Wn extends Wi{static description="You should never see this error"}class Jn extends Wi{static description="Host provided was not valid"}class Yn extends Wi{static description="Port provided was not valid"}class Xn extends zn{static description="QUIC config error"}class Zn extends zn{static description="QUIC Socket error"}class ea extends Zn{static description="QUIC Socket is not running"}class ta extends Zn{static description="QUIC Socket has active connections"}class ra extends Zn{static description="QUIC Socket cannot bind to the specified address"}class sa extends Zn{static description="QUIC Socket cannot send to the specified address"}class ia extends Zn{static description="QUIC Socket internal error"}class na extends zn{static description="QUIC Client error"}class aa extends na{static description="QUIC Client is destroyed"}class oa extends na{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class ca extends na{static description="QUIC Client had a failure relating to an invalid argument"}class la extends na{static description="QUIC Client cannot be created with the specified host"}class da extends na{static description="QUIC Client internal error"}class ua extends zn{static description="QUIC Server error"}class ha extends ua{static description="QUIC Server is not running"}class fa extends ua{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class ga extends ua{static description="QUIC Server creating a new connection"}class pa extends ua{static description="QUIC Server internal error"}class ba extends ua{static description="QUIC Server is stopping"}class ma extends zn{static description="QUIC Connection error"}class ya extends ma{static description="QUIC Connection is stopping"}class Aa extends ma{static description="QUIC Connection is not running"}class Ia extends ma{static description="QUIC Connection cannot be restarted because it has already been closed"}class va extends zn{static description="QUIC Connection start requires data when it is a server connection"}class wa extends ma{static description="QUIC connection invalid configuration"}class Sa extends ma{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class Ea extends Sa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Ca extends ma{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class ka extends Sa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class xa extends ma{static description="QUIC Connection max idle timeout exhausted"}class Ba extends ma{static description="QUIC Connection internal error"}class _a extends zn{static description="QUIC Stream error"}class Ra extends _a{static description="QUIC Stream is destroyed"}class Oa extends _a{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class Ua extends _a{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class Ta extends _a{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class Na extends _a{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class Da extends _a{static description="QUIC Stream internal error"}class Ma extends _a{static description="QUIC Stream limit has been reached"}const Pa=new TextEncoder,La=new TextDecoder("utf-8");function Ha(e){throw new Wn(e)}function Va(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 Ka(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Qa(e){const[t]=qn.Validator.isValidIPv4String(e);return t}function Fa(e){const[t]=qn.Validator.isValidIPv6String(e);return!!t||$a(e)}function $a(e){if(e.startsWith("::ffff:"))try{return qn.IPv6.fromString(e),!0}catch{if(Qa(e.slice(7)))return!0}return!1}function Ga(e){if(!Qa(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function ja(e){const t=e.slice(7);if(Qa(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 qa(e){const t=new qn.IPv4("0.0.0.0"),r=new qn.IPv6("::");if($a(e)){const r=ja(e);return new qn.IPv4(r).isEquals(t)?Ga("127.0.0.1"):e}return Qa(e)&&new qn.IPv4(e).isEquals(t)?"127.0.0.1":Fa(e)&&new qn.IPv6(e).isEquals(r)?"::1":e}async function za(e){return(await $n.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Wa(e,t){if(Qa(e))return[e,"udp4"];if(Fa(e))return[e,"udp6"];try{return Wa(e=await t(e),t)}catch{throw new Jn}}function Ja(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new Yn;return e}function Ya(e,t=0){let r;return r=Qa(e)?`${e}:${t}`:Fa(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Xa(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 a=$a(e),o=$a(r);if("ipv4&ipv6"===t&&"udp4"===s)return Ga(r);if("ipv4"===t){if(a){if("udp4"===s)return Ga(r);if("udp6"===s&&!o)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(o)return ja(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||o)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function Za(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(La.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(La.decode(r).trim()+"\n");return t}function eo(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function to(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function ro(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function so(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function io(e,t=1e5){Gn.setMaxListeners(t,e)}class no extends Si{}class ao extends no{}class oo extends ao{}class co extends ao{}class lo extends ao{}class uo extends no{}class ho extends uo{}class fo extends ao{}class go extends uo{}class po extends no{}class bo extends po{}class mo extends po{}class yo extends po{}class Ao extends no{}class Io extends Ao{}class vo extends Ao{}class wo extends Ao{}class So extends Ao{}class Eo extends Ao{}class Co extends no{}class ko extends Co{}class xo extends Co{}class Bo extends Co{}class _o extends Co{}class Ro extends Co{}var Oo=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let Uo=class{connectionMap=new Qn;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(to(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[dn]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=Fn.Header.fromSlice(e,Fn.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new Vn(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(Ji(e,e=>e instanceof Zn)){const t=new ia("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new co({detail:t})),void this.dispatchEvent(new lo)}if(e instanceof ga)return;throw e}}};constructor({resolveHostname:e=za,logger:t}){this.logger=t??new yi(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=Ka();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}={}){io(this[Ri]);let i=Ya(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,a]=await Wa(e,this.resolveHostname),o=Ja(t);this.socket=vi.createSocket({type:a,reuseAddr:r,ipv6Only:s}),this.socketBind=Va(this.socket.bind).bind(this.socket),this.socketClose=Va(this.socket.close).bind(this.socket),this.socketSend=Va(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=Ka();c.catch(()=>{}),this.socket.once("error",l);const d=this.socketBind(o,n);try{await Promise.race([d,c])}catch(t){throw new ra(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"===a||$a(n)?this._type="ipv4":"udp6"===a&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(co.name,this.handleEventQUICSocketError),this.addEventListener(lo.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=Ya(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=Ya(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new ta(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new lo),await this._closedP;const{p:r,resolveP:s}=Ka();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(co.name,this.handleEventQUICSocketError),this.removeEventListener(lo.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 Wa(r,this.resolveHostname);return s=qa(s),s=Xa(this._host,this._type,s,i,sa),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};Oo([Ln(new ea)],Uo.prototype,"host",null),Oo([Ln(new ea)],Uo.prototype,"port",null),Oo([Ln(new ea)],Uo.prototype,"type",null),Oo([Ln(new ea)],Uo.prototype,"send",null),Oo([Ln(new ea)],Uo.prototype,"send_",null),Uo=Oo([Pn({eventStart:class extends ao{},eventStarted:class extends ao{},eventStop:class extends ao{},eventStopped:oo})],Uo);const To=Uo,No=new WeakMap;const Do=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(No.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);No.set(i,r)};class Mo extends Wi{static description="Contexts error"}class Po extends Mo{static description="Aborted due to timer expiration"}const Lo=function(e=!1,t=1/0,r=Po){return(s,i,n)=>{const a=s.name??s.constructor.name,o=n.value;if("function"!=typeof o)throw new TypeError(`\`${a}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=No.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,a);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 en))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,a),function(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new en(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof en&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new en(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new $i((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}((e,...t)=>o.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}},Ho=["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(":"),Vo=1/0,Ko={sigalgs:Ho,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Fn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Fn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Fn.MAX_CONNECTION_WINDOW,maxStreamWindow:Fn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Qo={sigalgs:Ho,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Fn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Fn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Fn.MAX_CONNECTION_WINDOW,maxStreamWindow:Fn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Fo=t(import.meta.url)("stream/web");var $o=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};const Go=Symbol("abort readableP reason");let jo=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:a=new yi(`${this.name} ${t}`)}){a.info(`Create ${this.name}`);const o=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a});return"uni"===o.type&&("local"===e?(o.readableController.close(),o._readClosed=!0):"peer"===e&&(o.writable.close().catch(()=>{}),o._writeClosed=!0)),o.addEventListener(xo.name,o.handleEventQUICStreamError),o.addEventListener(Bo.name,o.handleEventQUICStreamCloseRead,{once:!0}),o.addEventListener(_o.name,o.handleEventQUICStreamCloseWrite,{once:!0}),a.info(`Created ${this.name}`),o}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 Da)throw this.logger.debug(to(t)),t;t instanceof Oa||t instanceof Ta?this.dispatchEvent(new Bo({detail:t})):(t instanceof Ua||t instanceof Na)&&this.dispatchEvent(new _o({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[hn]||"destroying"===this[gn]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[hn]||"destroying"===this[gn]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=a,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:o,resolveP:c}=Ka();if(this.closedP=o,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 Fo.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new Fo.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new Fo.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new Fo.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new Fo.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===ro(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new Ma(`Stream limit of ${t} has been reached`,{cause:e})}throw new Da(`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(xo.name,this.handleEventQUICStreamError),this.removeEventListener(Bo.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(_o.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=so(e))){const e=this.codeToReason("read",t),r=new Ta("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new xo({detail:r}))}{const t=new Da("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new xo({detail:t})),t}}if(null===e){const e=new Da("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new xo({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 Bo),void this.rejectReadableP?.(Go)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=ro(e))){this.connection.conn.streamShutdown(this.streamId,Fn.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new Na("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new xo({detail:r}))}{const t=new Da("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new xo({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}=Ka();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=so(e))){const e=this.codeToReason("read",t),r=new Ta("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new xo({detail:r}))}{const t=new Da("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new xo({detail:t})),t}}if(null===e){const e=new Da("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new xo({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 Bo)),this.dispatchEvent(new Ro)}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=ro(e))){const e=this.codeToReason("write",t),r=new Na("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new xo({detail:r}))}{const t=new Da("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new xo({detail:t})),t}}if(this.dispatchEvent(new Ro),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=Ka();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=ro(e))){const e=this.codeToReason("write",t),r=new Na("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new xo({detail:r}))}{const t=new Da("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new xo({detail:t})),t}}this.dispatchEvent(new _o),this.dispatchEvent(new Ro)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,Fn.Shutdown.Read,t)}catch(r){const e=new Da("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new xo({detail:e})),e}const r=new Oa("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new xo({detail:r})),this.dispatchEvent(new Ro)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,Fn.Shutdown.Write,t)}catch(r){const e=new Da("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new xo({detail:e})),e}const r=new Ua("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new xo({detail:r})),this.dispatchEvent(new Ro)}};$o([Mn(new Ra)],jo.prototype,"meta",null),$o([Mn(new Ra,!1,["destroying"])],jo.prototype,"read",null),$o([Mn(new Ra,!1,["destroying"])],jo.prototype,"write",null),jo=$o([Dn({eventDestroy:class extends Co{},eventDestroyed:ko})],jo);const qo=jo;var zo,Wo,Jo,Yo,Xo;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(zo||(zo={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Wo||(Wo={})),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"}(Jo||(Jo={})),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"}(Yo||(Yo={})),function(e){e[e.CloseNotify=256]="CloseNotify",e[e.UnexpectedMessage=266]="UnexpectedMessage",e[e.BadRecordMac=276]="BadRecordMac",e[e.RecordOverflow=278]="RecordOverflow",e[e.HandshakeFailure=296]="HandshakeFailure",e[e.BadCertificate=298]="BadCertificate",e[e.UnsupportedCertificate=299]="UnsupportedCertificate",e[e.CertificateRevoked=300]="CertificateRevoked",e[e.CertificateExpired=301]="CertificateExpired",e[e.CertificateUnknown=302]="CertificateUnknown",e[e.IllegalParameter=303]="IllegalParameter",e[e.UnknownCA=304]="UnknownCA",e[e.AccessDenied=305]="AccessDenied",e[e.DecodeError=306]="DecodeError",e[e.DecryptError=307]="DecryptError",e[e.ProtocolVersion=326]="ProtocolVersion",e[e.InsufficientSecurity=327]="InsufficientSecurity",e[e.InternalError=336]="InternalError",e[e.InappropriateFallback=342]="InappropriateFallback",e[e.UserCanceled=346]="UserCanceled",e[e.MissingExtension=365]="MissingExtension",e[e.UnsupportedExtension=366]="UnsupportedExtension",e[e.UnrecognizedName=368]="UnrecognizedName",e[e.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",e[e.UnknownPSKIdentity=371]="UnknownPSKIdentity",e[e.CertificateRequired=372]="CertificateRequired",e[e.NoApplicationProtocol=376]="NoApplicationProtocol"}(Xo||(Xo={}));var Zo=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let ec=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new on;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(to(t)),t instanceof Ba)throw t;this.dispatchEvent(new wo({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof Sa&&await this.send(),this[dn]&&"stopping"!==this[gn]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof Si&&!(e.detail instanceof Ro)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[dn]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(Ro.name,this.handleEventQUICStreamSend),t.removeEventListener(xi.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:a,reasonToCode:o=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new yi(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new wa("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const d=function(e){if(null!=e.key&&null==e.cert)throw new Xn("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new Xn("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 Xn("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Za(e.ca);t=Pa.encode(r.join(""))}null!=e.key&&(r=Za(e.key).map(e=>Pa.encode(e))),null!=e.cert&&(s=Za(e.cert).map(e=>Pa.encode(e)));try{i=Fn.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new Xn(`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=Fn.Connection.connect(s,t,{host:a.host,port:a.port},{host:i.host,port:i.port},d)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=Fn.Connection.accept(t,r,{host:a.host,port:a.port},{host:i.host,port:i.port},d)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=a,this.config=n,null!=this.config.cert){const e=Za(this.config.cert);this.certDERs=e.map(eo)}if(null!=this.config.ca){const e=Za(this.config.ca);this.caDERs=e.map(eo)}this.reasonToCode=o,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:h,resolveP:f,rejectP:g}=Ka();h.catch(()=>{}),this.secureEstablishedP=h,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=g;const{p,resolveP:b}=Ka();this.closedP=p,this.resolveClosedP=b}get connectionId(){const e=this.conn.sourceId();return new Vn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new Vn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new Vn(Buffer.concat([e,t])):new Vn(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 Ia;r.signal.throwIfAborted();const{p:s,rejectP:i}=Ka();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(vo.name,this.handleEventQUICConnectionError),this.addEventListener(wo.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new va("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,Fn.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,Fn.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,Yo.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new Sa("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new vo({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 Sa(i,{data:s});this.dispatchEvent(new vo({detail:n}))}await this.closedP,this.removeEventListener(vo.name,this.handleEventQUICConnectionError),this.removeEventListener(wo.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 Ba("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new vo({detail:t})),t}{let r;return r="TlsFail"===e.message?new Ea("Failed connection due to native TLS verification",{cause:e,data:t}):new Sa("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new vo({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 Ba("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new vo({detail:t})),t}this.dispatchEvent(new Eo({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 Ea("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new vo({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[gn]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=Fn.CRYPTO_ERROR_START&&e.errorCode<=Fn.CRYPTO_ERROR_STOP?this.dispatchEvent(new vo({detail:new ka(t,{data:e})})):this.dispatchEvent(new vo({detail:new Ca(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:Ha("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[dn]||"stopping"===this[gn]){this.conn.streamShutdown(e,Wo.Write,this.reasonToCode("write",ya)),this.conn.streamShutdown(e,Wo.Read,this.reasonToCode("read",ya));continue}this.isStreamUsed(e)&&Ha("We should never repeat streamIds when creating streams"),t=qo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${qo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Ro.name,this.handleEventQUICStreamSend),t.addEventListener(ko.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(xi.name,this.handleEventQUICStream),this.dispatchEvent(new So({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[dn]||"stopping"===this[gn]){this.conn.streamShutdown(e,Wo.Write,this.reasonToCode("write",ya)),this.conn.streamShutdown(e,Wo.Read,this.reasonToCode("read",ya));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==ro(e))continue;if("FinalSize"===e.message)continue;throw e}Ha("We never expect a duplicate stream to be readable")}t=qo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${qo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(Ro.name,this.handleEventQUICStreamSend),t.addEventListener(ko.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(xi.name,this.handleEventQUICStream),this.dispatchEvent(new So({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 vo({detail:new xa})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new en({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 vo({detail:new xa}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new en({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)&&Ha("We should never repeat streamIds when creating streams");const r=qo.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${qo.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(Ro.name,this.handleEventQUICStreamSend),r.addEventListener(ko.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(xi.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 en({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new en({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var tc,rc;Zo([Ln(new Aa)],ec.prototype,"connectionIdPeer",null),Zo([Ln(new Aa)],ec.prototype,"connectionIdShared",null),Zo([Lo(!0,Vo,class extends ma{static description="QUIC Connection start timeout"}),(tc=1,rc=Do,function(e,t){rc(e,t,tc)})],ec.prototype,"start",null),Zo([Ln(new Aa,!1,["starting","stopping"])],ec.prototype,"recv",null),Zo([Ln(new Aa,!1,["starting","stopping"])],ec.prototype,"send",null),Zo([Ln(new Aa)],ec.prototype,"newStream",null),ec=Zo([Pn({eventStart:class extends Ao{},eventStarted:class extends Ao{},eventStop:class extends Ao{},eventStopped:Io})],ec);const sc=ec;var ic=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let nc=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(to(t)),t instanceof pa)throw t;this.dispatchEvent(new yo({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof fa||this.isSocketShared)){this.socket.removeEventListener(oo.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new pa("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new mo({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[dn]&&"stopping"!==this[gn]&&(void 0!==t?await this.stop({isApp:!1,errorCode:Yo.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof Si&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new fa;this.removeEventListener(xi.name,this.handleEventQUICSocket),this.dispatchEvent(new mo({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Si&&!(e.detail instanceof Eo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[dn]&&"stopping"!==this.socket[gn])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 fo(`${fo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new mo({detail:new pa("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Eo.name,this.handleEventQUICConnectionSend),t.removeEventListener(xi.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=za,reasonToCode:i,codeToReason:n,minIdleTimeout:a,logger:o}){this.logger=o??new yi(this.constructor.name),this.crypto=e,null==r?(this.socket=new To({resolveHostname:s,logger:this.logger.getChild(To.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...Qo,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=a;const{p:c,resolveP:l}=Ka();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,io(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[dn])throw new fa;i=Ya(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=Ya(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=Ya(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(mo.name,this.handleEventQUICServerError),this.addEventListener(yo.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(oo.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(xi.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[dn]&&(i=Ya(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 ba),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 yo),await this._closedP;const{p:a,resolveP:o}=Ka();this._closedP=a,this.resolveClosedP=o,this.removeEventListener(mo.name,this.handleEventQUICServerError),this.removeEventListener(yo.name,this.handleEventQUICServerClose),this.socket.removeEventListener(oo.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(xi.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==Fn.Type.Initial&&t.ty!==Fn.Type.ZeroRTT)return;const i=new Vn(await this.crypto.ops.sign(this.crypto.key,r),0,Fn.MAX_CONN_ID_LEN),n=Ya(e.host,e.port);if(!Fn.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(Fn.MAX_DATAGRAM_SIZE),s=Fn.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new ga(`Failed to send version datagram ${n}`,{cause:e})}return}const a=t.token;if(0===a.byteLength){const s=await this.mintToken(r,e.host),a=Buffer.allocUnsafe(Fn.MAX_DATAGRAM_SIZE),o=Fn.retry(t.scid,t.dcid,i,s,t.version,a);try{await this.socket.send_(a,0,o,e.port,e.host)}catch(e){throw new ga(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const o=await this.validateToken(Buffer.from(a),e.host);if(null==o)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new Vn(t.dcid),l=new sc({type:"server",scid:c,dcid:o,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${sc.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(Eo.name,this.handleEventQUICConnectionSend),l.addEventListener(Io.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(xi.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(Eo.name,this.handleEventQUICConnectionSend),l.removeEventListener(Io.name,this.handleEventQUICConnectionStopped),l.removeEventListener(xi.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new ga("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new bo({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),a=Buffer.from(await r.ops.sign(r.key,n)),o={msg:n.toString("base64url"),sig:a.toString("base64url")},c=JSON.stringify(o);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 a;try{a=JSON.parse(i.toString())}catch{return}return"object"==typeof a&&null!=a&&"string"==typeof a.dcid&&"string"==typeof a.host&&a.host===t?Vn.fromString(a.dcid):void 0}(e,t,this.crypto)}};ic([Ln(new ha)],nc.prototype,"host",null),ic([Ln(new ha)],nc.prototype,"port",null),ic([Ln(new ha)],nc.prototype,"acceptConnection",null),nc=ic([Pn({eventStart:class extends po{},eventStarted:class extends po{},eventStop:class extends po{},eventStopped:class extends po{}})],nc);const ac=nc;var oc=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let cc=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:a,config:o={},resolveHostname:c=za,reuseAddr:l,ipv6Only:d,reasonToCode:u,codeToReason:h,logger:f=new yi(`${this.name}`)},g){let p=Ya(e,t);f.info(`Create ${this.name} to ${p}`);const b={...Ko,...o},m=new ArrayBuffer(Fn.MAX_CONN_ID_LEN);await a.ops.randomBytes(m);const y=new Vn(m);let[A,I]=await Wa(e,c);const v=Ja(t);let w,S;if(A=qa(A),null==n){const[e]=await Wa(s,c),t=Ja(i);n=new To({resolveHostname:c,logger:f.getChild(To.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:d})}else if(w=!0,!n[dn])throw new fa;try{A=Xa(n.host,n.type,A,I,la)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new sc({type:"client",scid:y,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:b,reasonToCode:u,codeToReason:h,logger:f.getChild(`${sc.name} ${y.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:f});w||n.addEventListener(xi.name,E.handleEventQUICSocket),n.addEventListener(oo.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(xi.name,E.handleEventQUICConnection),S.addEventListener(vo.name,E.handleEventQUICConnectionError),S.addEventListener(Eo.name,E.handleEventQUICConnectionSend),S.addEventListener(Io.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(ho.name,E.handleEventQUICClientError),E.addEventListener(go.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(g.signal.reason)};g.signal.aborted?C.abort(g.signal.reason):g.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new ca(void 0,{cause:e.detail}))}};E.addEventListener(`${fo.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:g.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(oo.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(xi.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(xi.name,E.handleEventQUICConnection),S.removeEventListener(vo.name,E.handleEventQUICConnectionError),S.removeEventListener(Eo.name,E.handleEventQUICConnectionSend),S.removeEventListener(Io.name,E.handleEventQUICConnectionStopped),E.removeEventListener(ho.name,E.handleEventQUICClientError),E.removeEventListener(go.name,E.handleEventQUICClientClose),e}finally{g.signal.removeEventListener("abort",k),E.removeEventListener(`${fo.name}-${S.sendId}`,x)}return p=Ya(A,t),f.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(to(t)),t instanceof da||t instanceof Ba)throw t;this.dispatchEvent(new go({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(vo.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:Yo.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof oa||this.isSocketShared)){this.socket.removeEventListener(oo.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new da("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new ho({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[hn]||"destroying"===this[gn]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof Si&&!(e.detail instanceof Eo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new oa;this.removeEventListener(xi.name,this.handleEventQUICSocket),this.dispatchEvent(new ho({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Si&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new ho({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[dn]||"stopping"===this.socket[gn])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 fo(`${fo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new ho({detail:new da("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(vo.name,this.handleEventQUICConnectionError),t.removeEventListener(Eo.name,this.handleEventQUICConnectionSend),t.removeEventListener(xi.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}=Ka();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[dn]&&(i=Ya(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(ho.name,this.handleEventQUICClientError),this.removeEventListener(go.name,this.handleEventQUICClientClose),this.socket.removeEventListener(oo.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(xi.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};oc([Mn(new aa)],cc.prototype,"host",null),oc([Mn(new aa)],cc.prototype,"port",null),oc([Mn(new aa)],cc.prototype,"localHost",null),oc([Mn(new aa)],cc.prototype,"localPort",null),oc([Lo(!0,Vo,class extends na{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,Do)],cc,"createQUICClient",null),cc=oc([Dn({eventDestroy:class extends uo{},eventDestroyed:class extends uo{}})],cc);const lc=cc,dc=t(import.meta.url)("node:crypto");var uc=a.n(dc);class hc{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=hc.toUint8Array(e),s=hc.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 fc="string",gc=/^[0-9a-f\s]+$/i,pc=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,bc=/^[a-zA-Z0-9-_]+$/;class mc{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=hc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class yc{static toString(e,t=!1){const r=hc.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 Ac{static isHex(e){return typeof e===fc&&gc.test(e)}static isBase64(e){return typeof e===fc&&pc.test(e)}static isBase64Url(e){return typeof e===fc&&bc.test(e)}static ToString(e,t="utf8"){const r=hc.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 yc.toString(r,!0);case"utf16":case"utf16be":return yc.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 yc.fromString(e,!0);case"utf16":case"utf16be":return yc.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=hc.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(!Ac.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(!Ac.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=Ac.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return mc.fromString(e);case"utf16":case"utf16be":return yc.fromString(e);case"utf16le":case"usc2":return yc.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Ac.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return mc.toString(e);case"utf16":case"utf16be":return yc.toString(e);case"utf16le":case"usc2":return yc.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=hc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=hc.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(!Ac.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 yc.toString(e,t)}static FromUtf16String(e,t=!1){return yc.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 Ic(...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 vc(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 wc(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 Sc(e,t,r=-1){const s=r;let i=e,n=0,a=Math.pow(2,t);for(let r=1;r<8;r++){if(e<a){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 a=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);a[n-e-1]=Math.floor(i/r),i-=a[n-e-1]*r}return e}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ec(...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 Cc(){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=wc(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,wc(n,8)-s}function kc(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 xc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Bc(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 _c(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)}Ac.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Rc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Bc(this.items)}}const Oc=[new Uint8Array([1])],Uc="0123456789",Tc="name",Nc="valueHexView",Dc="isHexOnly",Mc="idBlock",Pc="tagClass",Lc="tagNumber",Hc="isConstructed",Vc="fromBER",Kc="toBER",Qc="local",Fc="",$c=new ArrayBuffer(0),Gc=new Uint8Array(0),jc="EndOfContent",qc="OCTET STRING",zc="BIT STRING";function Wc(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?hc.toUint8Array(r.valueHex):Gc}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!_c(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",$c)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ac.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Jc{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=Fc,warnings:r=[],valueBeforeDecode:s=Gc}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=hc.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ac.ToHex(this.valueBeforeDecodeView)}}}Jc.NAME="baseBlock";class Yc extends Jc{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'")}}Yc.NAME="valueBlock";class Xc extends(Wc(Jc)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?hc.toUint8Array(e.valueHex):Gc,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",$c}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=Sc(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=hc.toUint8Array(e);if(!_c(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=wc(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}}}Xc.NAME="identificationBlock";class Zc extends Jc{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=hc.toUint8Array(e);if(!_c(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 a=t+1,o=s.subarray(a,a+n);return 0===o[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=wc(o,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=Sc(this.length,8);if(s.byteLength>127)return this.error="Too big length",$c;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}}}Zc.NAME="lengthBlock";const el={};class tl extends Jc{constructor({name:e=Fc,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Xc(s),this.lenBlock=new Zc(s),this.valueBlock=i?new i(s):new Yc(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 Rc;t||rl(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?$c: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():Ac.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Ac.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 rl(e){var t;if(e instanceof el.Constructed)for(const t of e.valueBlock.value)rl(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}tl.NAME="BaseBlock";class sl extends tl{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Fc,...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}'`}}sl.NAME="BaseStringBlock";class il extends(Wc(Yc)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var nl,al,ol,cl,ll,dl,ul,hl,fl,gl,pl,bl,ml,yl,Al,Il,vl,wl,Sl,El,Cl,kl,xl,Bl,_l,Rl,Ol,Ul,Tl,Nl,Dl,Ml,Pl,Ll,Hl,Vl;il.NAME="PrimitiveValueBlock";class Kl extends tl{constructor(e={}){super(e,il),this.idBlock.isConstructed=!1}}function Ql(e,t=0,r=e.length){const s=t;let i=new tl({},Yc);const n=new Jc;if(!_c(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 a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,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 o=tl;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};o=el.EndOfContent;break;case 1:o=el.Boolean;break;case 2:o=el.Integer;break;case 3:o=el.BitString;break;case 4:o=el.OctetString;break;case 5:o=el.Null;break;case 6:o=el.ObjectIdentifier;break;case 10:o=el.Enumerated;break;case 12:o=el.Utf8String;break;case 13:o=el.RelativeObjectIdentifier;break;case 14:o=el.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:o=el.Sequence;break;case 17:o=el.Set;break;case 18:o=el.NumericString;break;case 19:o=el.PrintableString;break;case 20:o=el.TeletexString;break;case 21:o=el.VideotexString;break;case 22:o=el.IA5String;break;case 23:o=el.UTCTime;break;case 24:o=el.GeneralizedTime;break;case 25:o=el.GraphicString;break;case 26:o=el.VisibleString;break;case 27:o=el.GeneralString;break;case 28:o=el.UniversalString;break;case 29:o=el.CharacterString;break;case 30:o=el.BmpString;break;case 31:o=el.DATE;break;case 32:o=el.TimeOfDay;break;case 33:o=el.DateTime;break;case 34:o=el.Duration;break;default:{const e=i.idBlock.isConstructed?new el.Constructed:new el.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else o=i.idBlock.isConstructed?el.Constructed:el.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,o),a=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:a,result:i}}function Fl(e){if(!e.byteLength){const e=new tl({},Yc);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ql(hc.toUint8Array(e).slice(),0,e.byteLength)}function $l(e,t){return e?1:t}nl=Kl,el.Primitive=nl,Kl.NAME="PRIMITIVE";class Gl extends Yc{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=hc.toUint8Array(e);if(!_c(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(;$l(this.isIndefiniteForm,r)>0;){const e=Ql(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===jc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===jc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Rc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?$c:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}Gl.NAME="ConstructedValueBlock";class jl extends tl{constructor(e={}){super(e,Gl),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} :`}}al=jl,el.Constructed=al,jl.NAME="CONSTRUCTED";class ql extends Yc{fromBER(e,t,r){return t}toBER(e){return $c}}ql.override="EndOfContentValueBlock";class zl extends tl{constructor(e={}){super(e,ql),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}ol=zl,el.EndOfContent=ol,zl.NAME=jc;class Wl extends tl{constructor(e={}){super(e,Yc),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}`}}cl=Wl,el.Null=cl,Wl.NAME="NULL";class Jl extends(Wc(Yc)){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=hc.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=hc.toUint8Array(e);return _c(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,Cc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Jl.NAME="BooleanValueBlock";class Yl extends tl{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Jl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}ll=Yl,el.Boolean=ll,Yl.NAME="BOOLEAN";class Xl extends(Wc(Gl)){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=Gl.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===jc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==qc)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?Gl.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Xl.NAME="OctetStringValueBlock";class Zl extends tl{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},Xl),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=Ql(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?jl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Ac.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 dl&&e.push(t.valueBlock.valueHexView);return hc.concat(e)}}dl=Zl,el.OctetString=dl,Zl.NAME=qc;class ed extends(Wc(Gl)){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=Gl.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===jc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==zc)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=hc.toUint8Array(e);if(!_c(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=Ql(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 Gl.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return $c;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}}}ed.NAME="BitStringValueBlock";class td extends tl{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},ed),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 jl.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 rd(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const a=n.length-1,o=i.slice(0),c=o.length-1;let l=0,d=0;for(let e=c<a?a:c;e>=0;e--,d++)l=1==d<o.length?n[a-d]+o[c-d]+r[0]:n[a-d]+r[0],r[0]=l/10,1==d>=n.length?n=Ec(new Uint8Array([l%10]),n):n[a-d]=l%10;return r[0]>0&&(n=Ec(r,n)),n}function sd(e){if(e>=Oc.length)for(let t=Oc.length;t<=e;t++){const e=new Uint8Array([0]);let r=Oc[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=Ec(e,r)),Oc.push(r)}return Oc[e]}function id(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),a=n.length-1,o=i.slice(0),c=o.length-1;let l,d=0;for(let e=c;e>=0;e--,d++)l=n[a-d]-o[c-d]-r,1==l<0?(r=1,n[a-d]=l+10):(r=0,n[a-d]=l);if(r>0)for(let e=a-c+1;e>=0;e--,d++){if(l=n[a-d]-r,!(l<0)){r=0,n[a-d]=l;break}r=1,n[a-d]=l+10}return n.slice()}ul=td,el.BitString=ul,td.NAME=zc;class nd extends(Wc(Yc)){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=Cc.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=Sc(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=Sc(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="",a=!1;for(let a=i.byteLength-1;a>=0;a--){t=i[a];for(let i=0;i<8;i++)1&~t||(s===e?(r=id(sd(s),r),n="-"):r=rd(r,sd(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(a=!0),a&&(n+=Uc.charAt(r[e]));return!1===a&&(n+=Uc.charAt(0)),n}}hl=nd,nd.NAME="IntegerValueBlock",Object.defineProperty(hl.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class ad extends tl{constructor(e={}){super(e,nd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return xc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){xc();const t=BigInt(e),r=new Rc,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Ac.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Ac.ToHex(e)}`)+t,n=hc.toUint8Array(Ac.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new fl({valueHex:r.final()})}convertToDER(){const e=new fl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new fl({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}fl=ad,el.Integer=fl,ad.NAME="INTEGER";class od extends ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}gl=od,el.Enumerated=gl,od.NAME="ENUMERATED";class cd extends(Wc(Yc)){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=hc.toUint8Array(e);if(!_c(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=wc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){xc();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=Sc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",$c;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=Ac.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}}}cd.NAME="sidBlock";class ld extends Yc{constructor({value:e=Fc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new cd;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,$c;t.push(s)}return Bc(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 cd;if(s>Number.MAX_SAFE_INTEGER){xc();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}}ld.NAME="ObjectIdentifierValueBlock";class dd extends tl{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ld),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}pl=dd,el.ObjectIdentifier=pl,dd.NAME="OBJECT IDENTIFIER";class ud extends(Wc(Jc)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=hc.toUint8Array(e);if(!_c(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=wc(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=Sc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",$c;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?Ac.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}ud.NAME="relativeSidBlock";class hd extends Yc{constructor({value:e=Fc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new ud;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,$c;r.push(s)}return Bc(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 ud;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}}hd.NAME="RelativeObjectIdentifierValueBlock";class fd extends tl{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,hd),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}bl=fd,el.RelativeObjectIdentifier=bl,fd.NAME="RelativeObjectIdentifier";class gd extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}ml=gd,el.Sequence=ml,gd.NAME="SEQUENCE";class pd extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}yl=pd,el.Set=yl,pd.NAME="SET";class bd extends(Wc(Yc)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Fc}toJSON(){return{...super.toJSON(),value:this.value}}}bd.NAME="StringValueBlock";class md extends bd{}md.NAME="SimpleStringValueBlock";class yd extends sl{constructor({...e}={}){super(e,md)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,hc.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}}yd.NAME="SIMPLE STRING";class Ad extends yd{fromBuffer(e){this.valueBlock.valueHexView=hc.toUint8Array(e);try{this.valueBlock.value=Ac.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Ac.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ac.FromUtf8String(e)),this.valueBlock.value=e}}Ad.NAME="Utf8StringValueBlock";class Id extends Ad{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Al=Id,el.Utf8String=Al,Id.NAME="UTF8String";class vd extends yd{fromBuffer(e){this.valueBlock.value=Ac.ToUtf16String(e),this.valueBlock.valueHexView=hc.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ac.FromUtf16String(e))}}vd.NAME="BmpStringValueBlock";class wd extends vd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Il=wd,el.BmpString=Il,wd.NAME="BMPString";class Sd extends yd{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=Sc(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}}Sd.NAME="UniversalStringValueBlock";class Ed extends Sd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}vl=Ed,el.UniversalString=vl,Ed.NAME="UniversalString";class Cd extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}wl=Cd,el.NumericString=wl,Cd.NAME="NumericString";class kd extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Sl=kd,el.PrintableString=Sl,kd.NAME="PrintableString";class xd extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}El=xd,el.TeletexString=El,xd.NAME="TeletexString";class Bd extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Cl=Bd,el.VideotexString=Cl,Bd.NAME="VideotexString";class _d extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}kl=_d,el.IA5String=kl,_d.NAME="IA5String";class Rd extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}xl=Rd,el.GraphicString=xl,Rd.NAME="GraphicString";class Od extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Bl=Od,el.VisibleString=Bl,Od.NAME="VisibleString";class Ud extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}_l=Ud,el.GeneralString=_l,Ud.NAME="GeneralString";class Td extends yd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Rl=Td,el.CharacterString=Rl,Td.NAME="CharacterString";class Nd extends Od{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,hc.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]=kc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=kc(this.month,2),e[2]=kc(this.day,2),e[3]=kc(this.hour,2),e[4]=kc(this.minute,2),e[5]=kc(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}}}Ol=Nd,el.UTCTime=Ol,Nd.NAME="UTCTime";class Dd extends Nd{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,a=0,o=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(a=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");o=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)+a;break;case 5:this.minute=parseInt(l[e],10)+o;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(kc(this.year,4)),e.push(kc(this.month,2)),e.push(kc(this.day,2)),e.push(kc(this.hour,2)),e.push(kc(this.minute,2)),e.push(kc(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(kc(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Ul=Dd,el.GeneralizedTime=Ul,Dd.NAME="GeneralizedTime";class Md extends Id{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Tl=Md,el.DATE=Tl,Md.NAME="DATE";class Pd extends Id{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Nl=Pd,el.TimeOfDay=Nl,Pd.NAME="TimeOfDay";class Ld extends Id{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Dl=Ld,el.DateTime=Dl,Ld.NAME="DateTime";class Hd extends Id{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Ml=Hd,el.Duration=Ml,Hd.NAME="Duration";class Vd extends Id{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Pl=Vd,el.TIME=Pl,Vd.NAME="TIME";class Kd{constructor({name:e=Fc,optional:t=!1}={}){this.name=e,this.optional=t}}class Qd extends Kd{constructor({value:e=[],...t}={}){super(t),this.value=e}}class Fd extends Kd{constructor({value:e=new Kd,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class $d{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=hc.toUint8Array(e)}constructor({data:e=Gc}={}){this.dataView=hc.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=hc.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function Gd(e,t,r){if(r instanceof Qd){for(const s of r.value)if(Gd(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Tc)&&(e.name=r.name),e}}if(r instanceof Kd)return r.hasOwnProperty(Tc)&&(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(Mc in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Vc in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Kc 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(Pc))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(Lc))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(Hc))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Dc 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(Nc 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,Fc),r.name&&(e[r.name]=t)),r instanceof el.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof Fd&&(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,Fc),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let a=0;a<n;a++)if(a-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[a].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,Fc),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof Fd){if(i=Gd(e,t.valueBlock.value[a],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,Fc),r.name&&delete e[r.name]),i;s++}if(Tc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=Qc 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[a])}}else if(i=Gd(e,t.valueBlock.value[a-s],r.valueBlock.value[a]),!1===i.verified){if(!r.valueBlock.value[a].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Fc),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,Fc),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&Nc in t.valueBlock){const s=Ql(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,Fc),r.name&&(delete e[r.name],t.name=r.name)),t}return Gd(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function jd(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=Ql(hc.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Gd(r.result,r.result,t)}(Vl=Ll||(Ll={}))[Vl.Sequence=0]="Sequence",Vl[Vl.Set=1]="Set",Vl[Vl.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"}(Hl||(Hl={}));class qd{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!hc.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=hc.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof td))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 td({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new td({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 zd{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):hc.isBufferSource(e)?this.buffer=hc.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Zl))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Zl({valueHex:this.buffer})}toSchema(e){return new Zl({name:e})}}const Wd={fromASN:e=>e instanceof Wl?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new Wl;const t=Fl(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Jd={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new ad({value:+e})},Yd={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new od({value:e})},Xd={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new ad({valueHex:e})},Zd={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new td({valueHex:e})},eu={fromASN:e=>e.valueBlock.toString(),toASN:e=>new dd({value:e})},tu={fromASN:e=>e.valueBlock.value,toASN:e=>new Yl({value:e})},ru={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Zl({valueHex:e})},su={fromASN:e=>new zd(e.getValue()),toASN:e=>e.toASN()};function iu(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const nu=iu(Id),au=iu(wd),ou=iu(Ed),cu=iu(Cd),lu=iu(kd),du=iu(xd),uu=iu(Bd),hu=iu(_d),fu=iu(Rd),gu=iu(Od),pu=iu(Ud),bu=iu(Td),mu={fromASN:e=>e.toDate(),toASN:e=>new Nd({valueDate:e})},yu={fromASN:e=>e.toDate(),toASN:e=>new Dd({valueDate:e})},Au={fromASN:()=>null,toASN:()=>new Wl};function Iu(e){switch(e){case Hl.Any:return Wd;case Hl.BitString:return Zd;case Hl.BmpString:return au;case Hl.Boolean:return tu;case Hl.CharacterString:return bu;case Hl.Enumerated:return Yd;case Hl.GeneralString:return pu;case Hl.GeneralizedTime:return yu;case Hl.GraphicString:return fu;case Hl.IA5String:return hu;case Hl.Integer:return Jd;case Hl.Null:return Au;case Hl.NumericString:return cu;case Hl.ObjectIdentifier:return eu;case Hl.OctetString:return ru;case Hl.PrintableString:return lu;case Hl.TeletexString:return du;case Hl.UTCTime:return mu;case Hl.UniversalString:return ou;case Hl.Utf8String:return nu;case Hl.VideotexString:return uu;case Hl.VisibleString:return gu;default:return null}}function vu(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||vu(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function wu(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||wu(r)}return!1}function Su(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 Eu=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:Ll.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 a;if("number"==typeof i.type){const e=Hl[i.type],t=o[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);a=new t({name:n})}else vu(i.type)?a=(new i.type).toSchema(n):i.optional?this.get(i.type).type===Ll.Choice?a=new Kd({name:n}):(a=this.create(i.type,!1),a.name=n):a=new Kd({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(a.name="",a=new("set"===i.repeated?pd:gd)({name:"",value:[new Fd({name:n,value:a})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||vu(i.type)){const e=i.repeated?jl:Kl;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?a:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new jl({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new jl({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,s.push(a)}switch(r.type){case Ll.Sequence:return new gd({value:s,name:""});case Ll.Set:return new pd({value:s,name:""});case Ll.Choice:return new Qd({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}},Cu=e=>t=>{let r;Eu.has(t)?r=Eu.get(t):(r=Eu.createDefault(t),Eu.set(t,r)),Object.assign(r,e)},ku=e=>(t,r)=>{let s;Eu.has(t.constructor)?s=Eu.get(t.constructor):(s=Eu.createDefault(t.constructor),Eu.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Iu(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 xu extends Error{constructor(){super(...arguments),this.schemas=[]}}class Bu{static parse(e,t){const r=Fl(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(vu(t))return(new t).fromASN(e);const s=Eu.get(t);Eu.cache(t);let i=s.schema;if(e.constructor===jl&&s.type!==Ll.Choice){i=new jl({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=Gd({},e,i);if(!n.verified)throw new xu(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const a=new t;if(wu(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=Iu(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||vu(c)){const s=null!==(r=i.converter)&&void 0!==r?r:vu(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?gd:pd);r.valueBlock=t.valueBlock;const n=Fl(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 o=n.result.valueBlock.value;a[e]=Array.from(o,e=>s.fromASN(e))}else a[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(vu(c))e=(new c).toSchema("");else{const t=Hl[c],r=o[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=Fl(e.toBER(!1)).result}a[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.");a[e]=Array.from(t,e=>this.fromASN(e,c))}else a[e]=this.fromASN(t,c)}return a}catch(e){throw e instanceof xu&&e.schemas.push(t.name),e}}}class _u{static serialize(e){return e instanceof tl?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&vu(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=Eu.get(t);Eu.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=Iu(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],a=e[s];if(void 0===a||n.defaultValue===a||"object"==typeof n.defaultValue&&"object"==typeof a&&Su(this.serialize(n.defaultValue),this.serialize(a)))continue;const o=_u.toAsnItem(n,s,t,a);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!vu(n.type))i.push(new jl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:o.valueBlock.value}));else{const e={};e.valueHex=o instanceof Wl?o.valueBeforeDecodeView:o.valueBlock.toBER(),i.push(new Kl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new jl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[o]}));else n.repeated?i=i.concat(o):i.push(o)}switch(r.type){case Ll.Sequence:s=new gd({value:i});break;case Ll.Set:s=new pd({value:i});break;case Ll.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 ${Hl[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?gd:pd)({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?gd:pd)({value:t})}else i=this.toASN(s);return i}}class Ru extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Ou{static serialize(e){return _u.serialize(e)}static parse(e,t){return Bu.parse(e,t)}static toString(e){const t=Fl(hc.isBufferSource(e)?hc.toArrayBuffer(e):Ou.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Uu(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class Tu extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class Nu extends Tu{constructor(e,t,r){super(t,r),this.schema=e}}class Du extends Nu{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class Mu extends Tu{}class Pu extends Tu{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class Lu extends Du{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var Hu;function Vu(e,t){if(!function(e,t){switch(t){case Hu.Boolean:return"boolean"==typeof e;case Hu.Number:return"number"==typeof e;case Hu.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${Hu[t]}`)}function Ku(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||Ku(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"}(Hu||(Hu={}));const Qu="default",Fu=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 $u{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 Mu("Incoming value must be string");if(!t.exec(e))throw new Mu(`Value doesn't match to pattern '${t.toString()}'`)}}class Gu{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Vu(e,Hu.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 Mu(`Value doesn't match to diapason [${e},${t}]`)}}}class ju{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Vu(e,Hu.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 Mu(`Value doesn't match to diapason (${e},${t})`)}}}class qu{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 Mu(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new Mu(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new Mu(`Value length must be exactly ${this.length}.`)}}class zu{constructor(e){this.enumeration=e}validate(e){if(Vu(e,Hu.String),!this.enumeration.includes(e))throw new Mu(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class Wu{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof qu&&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)Vu(e,t.type)}}static getSchemaByName(e,t=Qu){return{...e.names[Qu],...e.names[t]}}}class Ju extends Wu{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||Qu;if(Ku(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&&!Fu.has(s))throw new Tu("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,Fu.has(s)){const t=Fu.get(s);r={};const n=this.getSchemaByName(t,i);for(const a in n)try{const t=n[a],o=e[a];let c;if(t.optional&&void 0===o||void 0!==t.defaultValue&&o===t.defaultValue)continue;if(!t.optional&&void 0===o)throw new Pu(s.name,`Property '${a}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?o.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(o,e):o:t.repeated?o.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(o,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||a]=c}catch(e){throw e instanceof Pu?e:new Pu(t.target.name,`Property '${a}' 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 Yu extends Wu{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||Qu,i=new r;if(Ku(i))return i.fromJSON(e);const n=Fu.get(r),a=this.getSchemaByName(n,s),o={};t.strictProperty&&!Array.isArray(e)&&Yu.checkStrictProperty(e,a,n);for(const r in a)try{const o=a[r],c=o.name||r,l=e[c];if(void 0===l&&(o.optional||void 0!==o.defaultValue))continue;if(!o.optional&&void 0===l)throw new Du(n,`Property '${c}' is required.`);if(this.checkTypes(l,o),this.checkValues(l,o),"number"==typeof o.type)o.converter?o.repeated?i[r]=l.map(e=>o.converter.fromJSON(e,i)):i[r]=o.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:o.type,schemaName:s};o.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof Du||(e=new Du(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;o[r]=e}const c=Object.keys(o);if(c.length)throw new Lu(n,c,o);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 Lu(r,n)}}const Xu=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;Fu.has(t.constructor)?(i=Fu.get(t.constructor),i.target!==t.constructor&&(i=Fu.create(t.constructor),Fu.set(t.constructor,i))):(i=Fu.create(t.constructor),Fu.set(t.constructor,i));const n={type:Hu.Any,validations:[]},a=Object.assign(n,e);if(a.validations=function(e){const t=[];return e.pattern&&t.push(new $u(e.pattern)),e.type!==Hu.Number&&e.type!==Hu.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new Gu(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new ju(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new zu(e.enumeration))),(e.type===Hu.String||e.repeated||e.type===Hu.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new qu(e.length,e.minLength,e.maxLength))),t}(a),"number"!=typeof a.type&&!Fu.has(a.type)&&!Ku(a.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let o;o=Array.isArray(e.schema)?e.schema:[e.schema||Qu];for(const e of o)i.names[e]||(i.names[e]={}),i.names[e][r]=a};class Zu extends Error{}class eh extends Zu{}class th extends Zu{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class rh extends Zu{}class sh extends Zu{constructor(e){super(`${e}: Missing required property`)}}class ih{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Ac.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Ac.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 a=t.toUpperCase();return`-----BEGIN ${a}-----\n${n.join("\n")}\n-----END ${a}-----`}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 nh{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 th("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 th("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 th("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 th("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 th("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 th("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 rh("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new th("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 Zu("key: Is not extractable")}async onExportKey(e,t,...r){throw new th("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 th("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new eh("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 Zu("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new sh(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new rh(`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(!hc.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return hc.toArrayBuffer(e)}}class ah extends nh{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 oh extends ah{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 ch extends ah{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 rh("length: Must be more than 0")}}class lh extends ah{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 rh("length: Must be more than 0")}}class dh extends ah{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class uh extends ah{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 rh("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 rh("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class hh extends ah{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class fh extends nh{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 rh(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class gh extends nh{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=Ac.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 ph extends gh{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class bh extends gh{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 mh extends gh{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 yh extends nh{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 rh(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Ah extends yh{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 Ih=["secret","private","public"];class vh{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!==Ih.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class wh extends yh{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 vh))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new rh("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new rh(`public: Is not ${this.name} key`)}}class Sh extends wh{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class Eh extends yh{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Ch=class{constructor(e){e&&(this.value=e)}};Uu([ku({type:Hl.ObjectIdentifier})],Ch.prototype,"value",void 0),Ch=Uu([Cu({type:Ll.Choice})],Ch);class kh{constructor(e){Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],kh.prototype,"algorithm",void 0),Uu([ku({type:Hl.Any,optional:!0})],kh.prototype,"parameters",void 0);class xh{constructor(){this.version=0,this.privateKeyAlgorithm=new kh,this.privateKey=new ArrayBuffer(0)}}Uu([ku({type:Hl.Integer})],xh.prototype,"version",void 0),Uu([ku({type:kh})],xh.prototype,"privateKeyAlgorithm",void 0),Uu([ku({type:Hl.OctetString})],xh.prototype,"privateKey",void 0),Uu([ku({type:Hl.Any,optional:!0})],xh.prototype,"attributes",void 0);class Bh{constructor(){this.publicKeyAlgorithm=new kh,this.publicKey=new ArrayBuffer(0)}}Uu([ku({type:kh})],Bh.prototype,"publicKeyAlgorithm",void 0),Uu([ku({type:Hl.BitString})],Bh.prototype,"publicKey",void 0);const _h={fromJSON:e=>Ac.FromBase64Url(e),toJSON:e=>Ac.ToBase64Url(new Uint8Array(e))},Rh={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?Ic(new Uint8Array([0]).buffer,e):e;return new ad({valueHex:t})}};class Oh{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)}}Uu([ku({type:Hl.Integer,converter:Jd})],Oh.prototype,"version",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"n",converter:_h})],Oh.prototype,"modulus",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"e",converter:_h})],Oh.prototype,"publicExponent",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"d",converter:_h})],Oh.prototype,"privateExponent",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"p",converter:_h})],Oh.prototype,"prime1",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"q",converter:_h})],Oh.prototype,"prime2",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"dp",converter:_h})],Oh.prototype,"exponent1",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"dq",converter:_h})],Oh.prototype,"exponent2",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"qi",converter:_h})],Oh.prototype,"coefficient",void 0),Uu([ku({type:Hl.Any,optional:!0})],Oh.prototype,"otherPrimeInfos",void 0);class Uh{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"n",converter:_h})],Uh.prototype,"modulus",void 0),Uu([ku({type:Hl.Integer,converter:Rh}),Xu({name:"e",converter:_h})],Uh.prototype,"publicExponent",void 0);let Th=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 Zu("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Ac.ToBase64Url(e.buffer.slice(0,0+t)),y:Ac.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=Ac.FromBase64Url(e.x),r=Ac.FromBase64Url(e.y),s=Ic(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Uu([ku({type:Hl.OctetString})],Th.prototype,"value",void 0),Th=Uu([Cu({type:Ll.Choice})],Th);class Nh{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=Ac.FromBase64Url(e.d),"x"in e){const t=new Th;t.fromJSON(e);const r=_u.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Ac.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new Th(this.publicKey).toJSON()),e}}Uu([ku({type:Hl.Integer,converter:Jd})],Nh.prototype,"version",void 0),Uu([ku({type:Hl.OctetString})],Nh.prototype,"privateKey",void 0),Uu([ku({context:0,type:Hl.Any,optional:!0})],Nh.prototype,"parameters",void 0),Uu([ku({context:1,type:Hl.BitString,optional:!0})],Nh.prototype,"publicKey",void 0);const Dh={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 ad({valueHex:e.buffer})}return new ad({valueHex:e})}};var Mh=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:Dh});class Ph{static decodePoint(e,t){const r=hc.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=hc.toUint8Array(e.x),i=hc.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=hc.toUint8Array(e.r),i=hc.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=hc.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 Lh{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=Ph.decodeSignature(e,8*t),s=new Lh;return s.r=hc.toArrayBuffer(r.r),s.s=hc.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 Ph.encodeSignature(this,e).buffer}}Uu([ku({type:Hl.Integer,converter:Dh})],Lh.prototype,"r",void 0),Uu([ku({type:Hl.Integer,converter:Dh})],Lh.prototype,"s",void 0);class Hh extends xh{}Uu([ku({context:1,implicit:!0,type:Hl.BitString,optional:!0})],Hh.prototype,"publicKey",void 0);let Vh=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=Ac.FromBase64Url(e.d),this}toJSON(){return{d:Ac.ToBase64Url(this.value)}}};Uu([ku({type:Hl.OctetString})],Vh.prototype,"value",void 0),Vh=Uu([Cu({type:Ll.Choice})],Vh);let Kh=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Ac.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Ac.FromBase64Url(e.x),this}};Uu([ku({type:Hl.BitString})],Kh.prototype,"value",void 0),Kh=Uu([Cu({type:Ll.Choice})],Kh);let Qh=class{};Uu([ku({type:Hl.OctetString}),Xu({type:Hu.String,converter:_h})],Qh.prototype,"d",void 0),Qh=Uu([Cu({type:Ll.Choice})],Qh);const Fh="1.2.840.10045.3.1.7",$h="1.3.132.0",Gh=`${$h}.34`,jh=`${$h}.35`,qh=`${$h}.10`,zh="1.3.36.3.3.2.8.1.1",Wh=`${zh}.1`,Jh=`${zh}.2`,Yh=`${zh}.3`,Xh=`${zh}.4`,Zh=`${zh}.5`,ef=`${zh}.6`,tf=`${zh}.7`,rf=`${zh}.8`,sf=`${zh}.9`,nf=`${zh}.10`,af=`${zh}.11`,of=`${zh}.12`,cf=`${zh}.13`,lf=`${zh}.14`;var df=Object.freeze({__proto__:null,AlgorithmIdentifier:kh,get CurvePrivateKey(){return Qh},EcDsaSignature:Lh,EcPrivateKey:Nh,get EcPublicKey(){return Th},get EdPrivateKey(){return Vh},get EdPublicKey(){return Kh},get ObjectIdentifier(){return Ch},OneAsymmetricKey:Hh,PrivateKeyInfo:xh,PublicKeyInfo:Bh,RsaPrivateKey:Oh,RsaPublicKey:Uh,converters:Mh,idBrainpoolP160r1:Wh,idBrainpoolP160t1:Jh,idBrainpoolP192r1:Yh,idBrainpoolP192t1:Xh,idBrainpoolP224r1:Zh,idBrainpoolP224t1:ef,idBrainpoolP256r1:tf,idBrainpoolP256t1:rf,idBrainpoolP320r1:sf,idBrainpoolP320t1:nf,idBrainpoolP384r1:af,idBrainpoolP384t1:of,idBrainpoolP512r1:cf,idBrainpoolP512t1:lf,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:$h,idSecp256k1:qh,idSecp256r1:Fh,idSecp384r1:Gh,idSecp521r1:jh,idVersionOne:zh,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class uf{constructor(){}static register(e){const t=new Ch;t.value=e.id;const r=Ou.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}}uf.items=[],uf.names=[],uf.register({name:"P-256",id:Fh,size:256}),uf.register({name:"P-384",id:Gh,size:384}),uf.register({name:"P-521",id:jh,size:521}),uf.register({name:"K-256",id:qh,size:256}),uf.register({name:"brainpoolP160r1",id:Wh,size:160}),uf.register({name:"brainpoolP160t1",id:Jh,size:160}),uf.register({name:"brainpoolP192r1",id:Yh,size:192}),uf.register({name:"brainpoolP192t1",id:Xh,size:192}),uf.register({name:"brainpoolP224r1",id:Zh,size:224}),uf.register({name:"brainpoolP224t1",id:ef,size:224}),uf.register({name:"brainpoolP256r1",id:tf,size:256}),uf.register({name:"brainpoolP256t1",id:rf,size:256}),uf.register({name:"brainpoolP320r1",id:sf,size:320}),uf.register({name:"brainpoolP320t1",id:nf,size:320}),uf.register({name:"brainpoolP384r1",id:af,size:384}),uf.register({name:"brainpoolP384t1",id:of,size:384}),uf.register({name:"brainpoolP512r1",id:cf,size:512}),uf.register({name:"brainpoolP512t1",id:lf,size:512});class hf extends nh{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class ff extends nh{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class gf extends nh{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 pf extends nh{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 bf extends nh{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"),!hc.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!hc.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 mf extends nh{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 yf extends mf{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class Af extends mf{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class If{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=Ac.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class vf{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 wf={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},Sf=["pkcs8","spki","raw"];class Ef{constructor(){this.providers=new vf}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=hc.toArrayBuffer(r),a=this.getProvider(i.name);return await a.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),a=this.getProvider(n.name);return await a.generateKey({...n,name:a.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),a=hc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.sign({...n,name:o.name},r,a,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const a=this.prepareAlgorithm(t),o=hc.toArrayBuffer(i),c=hc.toArrayBuffer(s),l=this.getProvider(a.name);return await l.verify({...a,name:l.name},r,c,o,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),a=hc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.encrypt({...n,name:o.name},r,a,{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),a=hc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.decrypt({...n,name:o.name},r,a,{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),a=this.getProvider(n.name);return await a.deriveBits({...n,name:a.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...a]=e,o=this.prepareAlgorithm(s);this.getProvider(o.name).checkDerivedKeyParams(o);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const d=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...a);return this.importKey("raw",d,s,i,n,...a)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!wf[t])throw new TypeError("Invalid keyFormat argument");if(!wf[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,...a]=e,o=this.prepareAlgorithm(s),c=this.getProvider(o.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!Sf.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!hc.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...o,name:c.name},i,n,...a)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=Ac.FromUtf8String(e)}const a=this.prepareAlgorithm(s),o=hc.toArrayBuffer(n),c=this.getProvider(a.name);return c.encrypt({...a,name:c.name},r,o,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,a,...o){const c=this.prepareAlgorithm(s),l=hc.toArrayBuffer(t),d=this.getProvider(c.name);let u=await d.decrypt({...c,name:d.name},r,l,{keyUsage:!1},...o);if("jwk"===e)try{u=JSON.parse(Ac.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,a,...o)}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(Ef.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 eh("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof vh))throw new TypeError("Key is not of type 'CryptoKey'")}}const Cf=t(import.meta.url)("buffer"),kf=t(import.meta.url)("crypto");var xf=a.n(kf);const Bf=t(import.meta.url)("process"),_f={fromJSON:e=>Cf.Buffer.from(Ac.FromBase64Url(e)),toJSON:e=>Ac.ToBase64Url(e)};class Rf extends vh{constructor(){super(...arguments),this.data=Cf.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Uu([Xu({name:"ext",type:Hu.Boolean,optional:!0})],Rf.prototype,"extractable",void 0),Uu([Xu({name:"key_ops",type:Hu.String,repeated:!0,optional:!0})],Rf.prototype,"usages",void 0),Uu([Xu({type:Hu.String})],Rf.prototype,"kty",void 0),Uu([Xu({type:Hu.String,optional:!0})],Rf.prototype,"alg",void 0);class Of extends Rf{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class Uf extends Rf{}class Tf extends Of{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 eh("Unsupported algorithm name")}}set alg(e){}}Uu([Xu({name:"k",converter:_f})],Tf.prototype,"data",void 0);class Nf{static async generateKey(e,t,r){const s=new Tf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=xf().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof Tf))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return Ju.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new rh("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Yu.fromJSON(t,{targetSchema:Tf});break;case"raw":n=new Tf,n.data=Cf.Buffer.from(t);break;default:throw new rh("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 rh("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,Cf.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,Cf.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,Cf.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,Cf.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,Cf.Buffer.from(r));default:throw new rh("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Tf))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,Cf.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,Cf.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,Cf.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,Cf.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,Cf.Buffer.from(r));default:throw new rh("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=xf().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=xf().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=xf().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,Cf.Buffer.from(e.counter));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=xf().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=xf().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,Cf.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(Cf.Buffer.from(e.additionalData));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=xf().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),a=r.slice(r.length-s);e.additionalData&&i.setAAD(Cf.Buffer.from(e.additionalData)),i.setAuthTag(a);let o=i.update(n);return o=Cf.Buffer.concat([o,i.final()]),new Uint8Array(o).buffer}static async encryptAesKW(e,t,r){const s=xf().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=xf().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=xf().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=xf().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}Nf.AES_KW_IV=Cf.Buffer.from("A6A6A6A6A6A6A6A6","hex");const Df=new WeakMap;function Mf(e){const t=Df.get(e);if(!t)throw new rh("Cannot get CryptoKey from secure storage");return t}function Pf(e){const t=vh.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),Df.set(t,e),t}class Lf extends oh{async onGenerateKey(e,t,r){return Pf(await Nf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Nf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Nf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}const Hf=Cf.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Vf=Cf.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),Kf=16;function Qf(e){const t=Cf.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 Ff(e,t){const r=Math.min(e.length,t.length),s=Cf.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function $f(e,t){const r=xf().createCipheriv("aes"+(e.length<<3),e,Hf),s=r.update(t);return r.final(),s}function Gf(e,t){const r=Cf.Buffer.alloc(Kf),s=t*Kf,i=s+Kf;return e.copy(r,0,s,i),r}class jf extends ch{async onGenerateKey(e,t,r){return Pf(await Nf.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=$f(e,Hf);let r=Qf(t);128&t[0]&&(r=Ff(r,Vf));let s=Qf(r);return 128&r[0]&&(s=Ff(s,Vf)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/Kf);0===n?(n=1,s=!1):s=t.length%Kf===0;const a=n-1;i=s?Ff(Gf(t,a),r.subkey1):Ff(function(e,t){const r=Cf.Buffer.alloc(Kf),s=t*Kf,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,a),r.subkey2);let o,c=Hf;for(let r=0;r<a;r++)o=Ff(c,Gf(t,r)),c=$f(e,o);return o=Ff(i,c),$f(e,o)}(Mf(t).data,Cf.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===Cf.Buffer.from(r).compare(Cf.Buffer.from(i))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}class qf extends lh{async onGenerateKey(e,t,r){return Pf(await Nf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Nf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Nf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}class zf extends uh{async onGenerateKey(e,t,r){return Pf(await Nf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Nf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Nf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}class Wf extends hh{async onGenerateKey(e,t,r){return Pf(await Nf.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return Nf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Nf.decrypt(e,Mf(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}class Jf extends dh{async onGenerateKey(e,t,r){return Pf(await Nf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Nf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Nf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Nf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Nf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Tf))throw new TypeError("key: Is not a AesCryptoKey")}}class Yf extends Of{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new eh("Unsupported algorithm name")}}set alg(e){}}Uu([Xu({name:"k",converter:_f})],Yf.prototype,"data",void 0);class Xf{static async generateKey(e,t,r){const s=new Yf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=xf().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Ju.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new rh("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Yu.fromJSON(t,{targetSchema:Yf});break;case"raw":n=new Yf,n.data=Cf.Buffer.from(t);break;default:throw new rh("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,Cf.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,Cf.Buffer.from(r));default:throw new rh("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Yf))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,Cf.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,Cf.Buffer.from(r));default:throw new rh("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=xf().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=xf().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=xf().createCipheriv("des-ede3-cbc",t.data,Cf.Buffer.from(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=xf().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Cf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class Zf extends fh{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return Pf(await Xf.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return Xf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Xf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Xf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){const n=await Xf.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new rh("keyData: Wrong key size");return Pf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Yf))throw new TypeError("key: Is not a DesCryptoKey")}}class eg extends fh{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return Pf(await Xf.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return Xf.encrypt(e,Mf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Xf.decrypt(e,Mf(t),new Uint8Array(r))}async onExportKey(e,t){return Xf.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){const n=await Xf.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new rh("keyData: Wrong key size");return Pf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Yf))throw new TypeError("key: Is not a DesCryptoKey")}}function tg(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 rh("algorithm: Is not recognized")}}class rg extends Uf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Bu.parse(this.data,df.PrivateKeyInfo);return Bu.parse(e.privateKey,df.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:tg(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Ju.toJSON(e))}fromJSON(e){const t=Yu.fromJSON(e,{targetSchema:df.RsaPrivateKey}),r=new df.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=_u.serialize(t),this.data=Cf.Buffer.from(_u.serialize(r))}}class sg extends Uf{constructor(){super(...arguments),this.type="public"}getKey(){const e=Bu.parse(this.data,df.PublicKeyInfo);return Bu.parse(e.publicKey,df.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:tg(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Ju.toJSON(e))}fromJSON(e){const t=Yu.fromJSON(e,{targetSchema:df.RsaPublicKey}),r=new df.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=_u.serialize(t),this.data=Cf.Buffer.from(_u.serialize(r))}}class ig{static async generateKey(e,t,r){const s=new rg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new sg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=Cf.Buffer.concat([Cf.Buffer.alloc(4-e.publicExponent.byteLength,0),Cf.Buffer.from(e.publicExponent)]).readInt32BE(0),a=xf().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Ju.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new rh("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=Yu.fromJSON(t,{targetSchema:df.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Yu.fromJSON(t,{targetSchema:df.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=Bu.parse(new Uint8Array(t),df.PublicKeyInfo),n=Bu.parse(e.publicKey,df.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Bu.parse(new Uint8Array(t),df.PrivateKeyInfo),n=Bu.parse(e.privateKey,df.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new rh("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 rh("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 rh("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new rh("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new rh("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new df.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=_u.serialize(e);const n=new rg;return n.data=Cf.Buffer.from(_u.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 df.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=_u.serialize(e);const n=new sg;return n.data=Cf.Buffer.from(_u.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 rh("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=xf().createSign(s);i.update(Cf.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=xf().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const a=i.sign(n);return new Uint8Array(a).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=xf().createVerify(i);n.update(Cf.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(a.padding=xf().constants.RSA_PKCS1_PSS_PADDING,a.saltLength=e.saltLength),n.verify(a,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:xf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(xf().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:xf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(xf().privateDecrypt(s,r)).buffer}}ig.publicKeyUsages=["verify","encrypt","wrapKey"],ig.privateKeyUsages=["sign","decrypt","unwrapKey"];class ng extends ph{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 ig.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onSign(e,t,r){return ig.sign(e,Mf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return ig.verify(e,Mf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return ig.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof rg||r instanceof sg))throw new TypeError("key: Is not RSA CryptoKey")}}class ag extends bh{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 ig.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onSign(e,t,r){return ig.sign(e,Mf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return ig.verify(e,Mf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return ig.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof rg||r instanceof sg))throw new TypeError("key: Is not RSA CryptoKey")}}class og{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=xf().createHash(r).update(Cf.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class cg extends mh{async onGenerateKey(e,t,r){const s=await ig.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onEncrypt(e,t,r){const s=Mf(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),a=og.size(s.algorithm.hash)>>3,o=i.byteLength,c=n-o-2*a-2;if(o>n-2*a-2)throw new Error("Data too large");const l=new Uint8Array(n),d=l.subarray(1,a+1),u=l.subarray(a+1);u.set(i,a+c+1);const h=xf().createHash(s.algorithm.hash.name.replace("-","")).update(hc.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(h,0),u[a+c]=1,xf().randomFillSync(d);const f=this.mgf1(s.algorithm.hash,d,u.length);for(let e=0;e<u.length;e++)u[e]^=f[e];const g=this.mgf1(s.algorithm.hash,u,d.length);for(let e=0;e<d.length;e++)d[e]^=g[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=xf().publicEncrypt({key:s.pem,padding:xf().constants.RSA_NO_PADDING},Cf.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=Mf(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=og.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 a=xf().privateDecrypt({key:s.pem,padding:xf().constants.RSA_NO_PADDING},Cf.Buffer.from(r));const o=a[0],c=a.subarray(1,n+1),l=a.subarray(n+1);if(0!==o)throw new Error("Decryption failed");const d=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=d[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const h=xf().createHash(s.algorithm.hash.name.replace("-","")).update(hc.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(h[e]!==l[e])throw new Error("Decryption failed");let f=n;for(;f<l.length;f++){const e=l[f];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(f===l.length)throw new Error("Decryption failed");return a=l.subarray(f+1),new Uint8Array(a).buffer}async onExportKey(e,t){return ig.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof rg||r instanceof sg))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=og.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),a=Math.ceil(r/s);for(let r=0;r<a;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const a=i.subarray(r*s);let o=xf().createHash(e.name.replace("-","")).update(t).update(n).digest();o.length>a.length&&(o=o.subarray(0,a.length)),a.set(o)}return i}}class lg extends nh{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 ig.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(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=Ac.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=xf().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=xf().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return ig.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await ig.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof rg||r instanceof sg))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${Mf(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:xf().constants.RSA_PKCS1_PADDING}}}const dg={"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 ug(e){const t=dg[e];if(!t)throw new rh(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class hg extends Uf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Bu.parse(this.data,df.PrivateKeyInfo);return Bu.parse(e.privateKey,df.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Ju.toJSON(e))}fromJSON(e){if(!e.crv)throw new rh("Cannot get named curve from JWK. Property 'crv' is required");const t=new df.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=_u.serialize(new df.ObjectIdentifier(ug(e.crv)));const r=Yu.fromJSON(e,{targetSchema:df.EcPrivateKey});return t.privateKey=_u.serialize(r),this.data=Cf.Buffer.from(_u.serialize(t)),this}}class fg extends Uf{constructor(){super(...arguments),this.type="public"}getKey(){const e=Bu.parse(this.data,df.PublicKeyInfo);return new df.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,Ju.toJSON(e))}fromJSON(e){if(!e.crv)throw new rh("Cannot get named curve from JWK. Property 'crv' is required");const t=Yu.fromJSON(e,{targetSchema:df.EcPublicKey}),r=new df.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=_u.serialize(new df.ObjectIdentifier(ug(e.crv))),r.publicKey=_u.toASN(t).valueHex,this.data=Cf.Buffer.from(_u.serialize(r)),this}}class gg extends nh{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class pg extends nh{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class bg extends nh{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class mg extends nh{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class yg extends nh{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class Ag extends nh{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class Ig extends nh{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return og.digest(e,t)}}class vg{static async generateKey(e,t,r){const s=new hg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new fg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=xf().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=og.getAlgorithmName(e.hash),i=xf().createSign(s);i.update(Cf.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},a=i.sign(n),o=Bu.parse(a,df.EcDsaSignature);return Ph.encodeSignature(o,uf.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=og.getAlgorithmName(e.hash),n=xf().createVerify(i);n.update(Cf.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem},o=new df.EcDsaSignature,c=uf.get(t.algorithm.namedCurve),l=Ph.decodeSignature(r,c.size);o.r=hc.toArrayBuffer(l.r),o.s=hc.toArrayBuffer(l.s);const d=Cf.Buffer.from(_u.serialize(o));return n.verify(a,d)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=xf().createECDH(s),n=Bu.parse(t.data,df.PrivateKeyInfo),a=Bu.parse(n.privateKey,df.EcPrivateKey);i.setPrivateKey(Cf.Buffer.from(a.privateKey));const o=Bu.parse(e.public.data,df.PublicKeyInfo),c=i.computeSecret(Cf.Buffer.from(o.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Ju.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Bu.parse(t.data,df.PublicKeyInfo).publicKey;default:throw new rh("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=Yu.fromJSON(t,{targetSchema:df.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Yu.fromJSON(t,{targetSchema:df.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new df.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=Bu.parse(new Uint8Array(t),df.PublicKeyInfo),n=new df.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Bu.parse(new Uint8Array(t),df.PrivateKeyInfo),n=Bu.parse(e.privateKey,df.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new rh("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Zu("Key info doesn't have required parameters");let r="";try{r=Bu.parse(e,df.ObjectIdentifier).value}catch(e){throw new Zu("Cannot read key info parameters")}if(ug(t)!==r)throw new Zu("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new df.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=_u.serialize(new df.ObjectIdentifier(ug(t.namedCurve))),i.privateKey=_u.serialize(e);const n=new hg;return n.data=Cf.Buffer.from(_u.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new df.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=ug(t.namedCurve);i.publicKeyAlgorithm.parameters=_u.serialize(new df.ObjectIdentifier(n)),i.publicKey=e.value;const a=new fg;return a.data=Cf.Buffer.from(_u.serialize(i)),a.algorithm=Object.assign({},t),a.extractable=r,a.usages=s,a}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}}}vg.publicKeyUsages=["verify"],vg.privateKeyUsages=["sign","deriveKey","deriveBits"];class wg extends Ah{constructor(){super(...arguments),this.namedCurves=uf.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 vg.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onSign(e,t,r){return vg.sign(e,Mf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return vg.verify(e,Mf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return vg.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await vg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof hg||r instanceof fg))throw new TypeError("key: Is not EC CryptoKey")}}class Sg extends wh{constructor(){super(...arguments),this.namedCurves=uf.names}async onGenerateKey(e,t,r){const s=await vg.generateKey({...e,name:this.name},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onExportKey(e,t){return vg.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await vg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Mf(e);if(!(r instanceof hg||r instanceof fg))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await vg.deriveBits({...e,public:Mf(e.public)},Mf(t),r)}}const Eg={[df.idEd448]:"Ed448",ed448:df.idEd448,[df.idX448]:"X448",x448:df.idX448,[df.idEd25519]:"Ed25519",ed25519:df.idEd25519,[df.idX25519]:"X25519",x25519:df.idX25519};function Cg(e){const t=Eg[e.toLowerCase()];if(!t)throw new rh(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class kg extends Uf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Bu.parse(this.data,df.PrivateKeyInfo);return Bu.parse(e.privateKey,df.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Ju.toJSON(e))}fromJSON(e){if(!e.crv)throw new rh("Cannot get named curve from JWK. Property 'crv' is required");const t=new df.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=Cg(e.crv);const r=Yu.fromJSON(e,{targetSchema:df.CurvePrivateKey});return t.privateKey=_u.serialize(r),this.data=Cf.Buffer.from(_u.serialize(t)),this}}class xg extends Uf{constructor(){super(...arguments),this.type="public"}getKey(){return Bu.parse(this.data,df.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:Ac.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new rh("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new rh("Cannot get property from JWK. Property 'x' is required");const t=new df.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=Cg(e.crv),t.publicKey=Ac.FromBase64Url(e.x),this.data=Cf.Buffer.from(_u.serialize(t)),this}}class Bg{static async generateKey(e,t,r){const s=new kg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new xg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),a=xf().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.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=xf().sign(null,Cf.Buffer.from(r),s);return hc.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 xf().verify(null,Cf.Buffer.from(s),i,Cf.Buffer.from(r))}static async deriveBits(e,t,r){const s=xf().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=xf().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=xf().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 Ju.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Bu.parse(t.data,df.PublicKeyInfo).publicKey;default:throw new rh("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=Yu.fromJSON(t,{targetSchema:df.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Ac.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=Bu.parse(new Uint8Array(t),df.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=Bu.parse(new Uint8Array(t),df.PrivateKeyInfo),n=Bu.parse(e.privateKey,df.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new rh("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new kg;return i.fromJSON({crv:t.namedCurve,d:Ac.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 xg;return i.fromJSON({crv:t.namedCurve,x:Ac.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}Bg.publicKeyUsages=["verify"],Bg.privateKeyUsages=["sign","deriveKey","deriveBits"];class _g extends Eh{async onGenerateKey(e,t,r){const s=await Bg.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onSign(e,t,r){return Bg.sign(e,Mf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Bg.verify(e,Mf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Bg.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Bg.importKey(e,t,{...r,name:this.name},s,i))}}class Rg extends Sh{async onGenerateKey(e,t,r){const s=await Bg.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onDeriveBits(e,t,r){return await Bg.deriveBits({...e,public:Mf(e.public)},Mf(t),r)}async onExportKey(e,t){return Bg.exportKey(e,Mf(t))}async onImportKey(e,t,r,s,i){return Pf(await Bg.importKey(e,t,{...r,name:this.name},s,i))}}class Og extends Rf{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 Ug extends Og{constructor(){super(...arguments),this.type="private"}toJWK(){const e=xf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=ih.toUint8Array(this.data.toString()),r=Ou.parse(t,df.PrivateKeyInfo),s=Ou.parse(r.privateKey,df.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class Tg extends Og{constructor(){super(...arguments),this.type="public"}toJWK(){const e=xf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class Ng{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=xf().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},a=r.filter(e=>this.privateKeyUsages.includes(e)),o=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new Ug(n,t,a,i.privateKey),publicKey:new Tg(n,!0,o,i.publicKey)}}static async sign(e,t,r){const s=xf().sign(null,Buffer.from(r),t.data);return hc.toArrayBuffer(s)}static async verify(e,t,r,s){return xf().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 ih.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Ac.FromBase64Url(e.x)}default:return Promise.reject(new rh("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 df.EdPrivateKey;t.value=hc.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new df.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?df.idEd25519:df.idX25519,n.privateKey=Ou.serialize(t);const a=Ou.serialize(n),o=ih.fromBufferSource(a,"PRIVATE KEY");return new Ug(r,s,i,o)}if(e.x){const t=xf().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new Tg(r,s,i,t)}throw new rh("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=ih.fromBufferSource(t,"PRIVATE KEY");return new Ug(r,s,i,e)}case"spki":{const e=ih.fromBufferSource(t,"PUBLIC KEY");return new Tg(r,s,i,e)}case"raw":{const e=t,n=xf().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Ac.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new Tg(r,s,i,n)}default:return Promise.reject(new rh("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}Ng.privateKeyUsages=["sign","deriveBits","deriveKey"],Ng.publicKeyUsages=["verify"];class Dg extends ff{async onGenerateKey(e,t,r){const s=await Ng.generateKey(e,t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onSign(e,t,r){const s=Mf(t);return Ng.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=Mf(t);return Ng.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=Mf(t);return Ng.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Pf(await Ng.importKey(e,t,r,s,i))}}class Mg extends hf{async onGenerateKey(e,t,r){const s=await Ng.generateKey(e,t,r);return{privateKey:Pf(s.privateKey),publicKey:Pf(s.publicKey)}}async onDeriveBits(e,t,r){const s=Mf(t),i=Mf(e.public),n=xf().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),a=xf().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),o=xf().diffieHellman({publicKey:n,privateKey:a});return new Uint8Array(o).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=Mf(t);return Ng.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Pf(await Ng.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Og))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class Pg extends Rf{}class Lg extends pf{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=hc.toArrayBuffer(e.salt),a=e.hash.name.replace("-","");xf().pbkdf2(Mf(t).data,Cf.Buffer.from(n),e.iterations,r>>3,a,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new Pg;return e.data=Cf.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,Pf(e)}throw new rh("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Pg))throw new TypeError("key: Is not PBKDF CryptoKey")}}class Hg extends Rf{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Uu([Xu({name:"k",converter:_f})],Hg.prototype,"data",void 0);class Vg extends gf{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new Hg;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=xf().randomBytes(s>>3),Pf(i)}async onSign(e,t,r){const s=og.getAlgorithmName(t.algorithm.hash),i=xf().createHmac(s,Mf(t).data).update(Cf.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=og.getAlgorithmName(t.algorithm.hash);return 0===xf().createHmac(i,Mf(t).data).update(Cf.Buffer.from(s)).digest().compare(Cf.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Yu.fromJSON(t,{targetSchema:Hg});break;case"raw":n=new Hg,n.data=Cf.Buffer.from(t);break;default:throw new rh("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,Pf(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return Ju.toJSON(Mf(t));case"raw":return new Uint8Array(Mf(t).data).buffer;default:throw new rh("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Hg))throw new TypeError("key: Is not HMAC CryptoKey")}}class Kg extends Rf{}class Qg extends bf{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new rh("Operation not supported");const n=new Kg;return n.data=Cf.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,Pf(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=xf().createHash(s).digest().length,n=r/8,a=hc.toUint8Array(e.info),o=xf().createHmac(s,hc.toUint8Array(e.salt)).update(hc.toUint8Array(Mf(t).data)).digest(),c=[Cf.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(xf().createHmac(s,o).update(Cf.Buffer.concat([c[e-1],a,Cf.Buffer.from([e])])).digest());return Cf.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Mf(e)instanceof Kg))throw new TypeError("key: Is not HKDF CryptoKey")}}class Fg{static digest(e,t){const r=xf().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(Cf.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class $g extends yf{async onDigest(e,t){return Fg.digest(e,t)}}class Gg extends Af{async onDigest(e,t){return Fg.digest(e,t)}}class jg extends Ef{constructor(){var e;super(),this.providers.set(new Lf),this.providers.set(new qf),this.providers.set(new zf),this.providers.set(new jf),this.providers.set(new Wf),this.providers.set(new Jf),xf().getCiphers().includes("des-cbc")&&this.providers.set(new Zf),this.providers.set(new eg),this.providers.set(new ng),this.providers.set(new ag),this.providers.set(new cg),this.providers.set(new lg),this.providers.set(new wg),this.providers.set(new Sg),this.providers.set(new gg),this.providers.set(new pg),this.providers.set(new bg),this.providers.set(new mg),this.providers.set(new Lg),this.providers.set(new Vg),this.providers.set(new Qg);const t=null===(e=/^v(\d+)/.exec(Bf.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new $g),this.providers.set(new Gg));const r=xf().getHashes();r.includes("sha3-256")&&this.providers.set(new yg),r.includes("sha3-384")&&this.providers.set(new Ag),r.includes("sha3-512")&&this.providers.set(new Ig),t&&parseInt(t,10)>=14&&(this.providers.set(new _g),this.providers.set(new Rg),this.providers.set(new Dg),this.providers.set(new Mg))}}var qg,zg,Wg;a(909);class Jg{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(Ac.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 Yg=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Uu([ku({type:Hl.TeletexString})],Yg.prototype,"teletexString",void 0),Uu([ku({type:Hl.PrintableString})],Yg.prototype,"printableString",void 0),Uu([ku({type:Hl.UniversalString})],Yg.prototype,"universalString",void 0),Uu([ku({type:Hl.Utf8String})],Yg.prototype,"utf8String",void 0),Uu([ku({type:Hl.BmpString})],Yg.prototype,"bmpString",void 0),Yg=Uu([Cu({type:Ll.Choice})],Yg);let Xg=class extends Yg{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Ac.ToHex(this.anyValue):super.toString())}};Uu([ku({type:Hl.IA5String})],Xg.prototype,"ia5String",void 0),Uu([ku({type:Hl.Any})],Xg.prototype,"anyValue",void 0),Xg=Uu([Cu({type:Ll.Choice})],Xg);class Zg{constructor(e={}){this.type="",this.value=new Xg,Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Zg.prototype,"type",void 0),Uu([ku({type:Xg})],Zg.prototype,"value",void 0);let ep=qg=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,qg.prototype)}};ep=qg=Uu([Cu({type:Ll.Set,itemType:Zg})],ep);let tp=zg=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,zg.prototype)}};tp=zg=Uu([Cu({type:Ll.Sequence,itemType:ep})],tp);let rp=Wg=class extends tp{constructor(e){super(e),Object.setPrototypeOf(this,Wg.prototype)}};rp=Wg=Uu([Cu({type:Ll.Sequence})],rp);const sp={fromASN:e=>Jg.toString(ru.fromASN(e)),toASN:e=>ru.toASN(Jg.fromString(e))};class ip{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],ip.prototype,"typeId",void 0),Uu([ku({type:Hl.Any,context:0})],ip.prototype,"value",void 0);class np{constructor(e={}){this.partyName=new Yg,Object.assign(this,e)}}Uu([ku({type:Yg,optional:!0,context:0,implicit:!0})],np.prototype,"nameAssigner",void 0),Uu([ku({type:Yg,context:1,implicit:!0})],np.prototype,"partyName",void 0);let ap=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:ip,context:0,implicit:!0})],ap.prototype,"otherName",void 0),Uu([ku({type:Hl.IA5String,context:1,implicit:!0})],ap.prototype,"rfc822Name",void 0),Uu([ku({type:Hl.IA5String,context:2,implicit:!0})],ap.prototype,"dNSName",void 0),Uu([ku({type:Hl.Any,context:3,implicit:!0})],ap.prototype,"x400Address",void 0),Uu([ku({type:rp,context:4,implicit:!1})],ap.prototype,"directoryName",void 0),Uu([ku({type:np,context:5})],ap.prototype,"ediPartyName",void 0),Uu([ku({type:Hl.IA5String,context:6,implicit:!0})],ap.prototype,"uniformResourceIdentifier",void 0),Uu([ku({type:Hl.OctetString,context:7,implicit:!0,converter:sp})],ap.prototype,"iPAddress",void 0),Uu([ku({type:Hl.ObjectIdentifier,context:8,implicit:!0})],ap.prototype,"registeredID",void 0),ap=Uu([Cu({type:Ll.Choice})],ap);const op="1.3.6.1.5.5.7",cp=`${op}.3`,lp=`${op}.48`,dp=`${lp}.1`,up=`${lp}.2`,hp=`${lp}.3`,fp=`${lp}.5`,gp="2.5.29";var pp;const bp=`${op}.1.1`;class mp{constructor(e={}){this.accessMethod="",this.accessLocation=new ap,Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],mp.prototype,"accessMethod",void 0),Uu([ku({type:ap})],mp.prototype,"accessLocation",void 0);let yp=pp=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,pp.prototype)}};yp=pp=Uu([Cu({type:Ll.Sequence,itemType:mp})],yp);const Ap=`${gp}.35`;class Ip extends zd{}class vp{constructor(e={}){e&&Object.assign(this,e)}}Uu([ku({type:Ip,context:0,optional:!0,implicit:!0})],vp.prototype,"keyIdentifier",void 0),Uu([ku({type:ap,context:1,optional:!0,implicit:!0,repeated:"sequence"})],vp.prototype,"authorityCertIssuer",void 0),Uu([ku({type:Hl.Integer,context:2,optional:!0,implicit:!0,converter:Xd})],vp.prototype,"authorityCertSerialNumber",void 0);const wp=`${gp}.19`;class Sp{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Ep;Uu([ku({type:Hl.Boolean,defaultValue:!1})],Sp.prototype,"cA",void 0),Uu([ku({type:Hl.Integer,optional:!0})],Sp.prototype,"pathLenConstraint",void 0);let Cp=Ep=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Ep.prototype)}};var kp;Cp=Ep=Uu([Cu({type:Ll.Sequence,itemType:ap})],Cp);let xp=kp=class extends Cp{constructor(e){super(e),Object.setPrototypeOf(this,kp.prototype)}};var Bp;xp=kp=Uu([Cu({type:Ll.Sequence})],xp);const _p=`${gp}.32`;let Rp=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Uu([ku({type:Hl.IA5String})],Rp.prototype,"ia5String",void 0),Uu([ku({type:Hl.VisibleString})],Rp.prototype,"visibleString",void 0),Uu([ku({type:Hl.BmpString})],Rp.prototype,"bmpString",void 0),Uu([ku({type:Hl.Utf8String})],Rp.prototype,"utf8String",void 0),Rp=Uu([Cu({type:Ll.Choice})],Rp);class Op{constructor(e={}){this.organization=new Rp,this.noticeNumbers=[],Object.assign(this,e)}}Uu([ku({type:Rp})],Op.prototype,"organization",void 0),Uu([ku({type:Hl.Integer,repeated:"sequence"})],Op.prototype,"noticeNumbers",void 0);class Up{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:Op,optional:!0})],Up.prototype,"noticeRef",void 0),Uu([ku({type:Rp,optional:!0})],Up.prototype,"explicitText",void 0);let Tp=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:Hl.IA5String})],Tp.prototype,"cPSuri",void 0),Uu([ku({type:Up})],Tp.prototype,"userNotice",void 0),Tp=Uu([Cu({type:Ll.Choice})],Tp);class Np{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Np.prototype,"policyQualifierId",void 0),Uu([ku({type:Hl.Any})],Np.prototype,"qualifier",void 0);class Dp{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Dp.prototype,"policyIdentifier",void 0),Uu([ku({type:Np,repeated:"sequence",optional:!0})],Dp.prototype,"policyQualifiers",void 0);let Mp=Bp=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Bp.prototype)}};Mp=Bp=Uu([Cu({type:Ll.Sequence,itemType:Dp})],Mp);let Pp=class{constructor(e=0){this.value=e}};Uu([ku({type:Hl.Integer})],Pp.prototype,"value",void 0),Pp=Uu([Cu({type:Ll.Choice})],Pp);let Lp=class extends Pp{};var Hp;Lp=Uu([Cu({type:Ll.Choice})],Lp);const Vp=`${gp}.31`;var Kp;!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"}(Kp||(Kp={}));class Qp extends qd{toJSON(){const e=[],t=this.toNumber();return t&Kp.aACompromise&&e.push("aACompromise"),t&Kp.affiliationChanged&&e.push("affiliationChanged"),t&Kp.cACompromise&&e.push("cACompromise"),t&Kp.certificateHold&&e.push("certificateHold"),t&Kp.cessationOfOperation&&e.push("cessationOfOperation"),t&Kp.keyCompromise&&e.push("keyCompromise"),t&Kp.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&Kp.superseded&&e.push("superseded"),t&Kp.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let Fp=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:ap,context:0,repeated:"sequence",implicit:!0})],Fp.prototype,"fullName",void 0),Uu([ku({type:ep,context:1,implicit:!0})],Fp.prototype,"nameRelativeToCRLIssuer",void 0),Fp=Uu([Cu({type:Ll.Choice})],Fp);class $p{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:Fp,context:0,optional:!0})],$p.prototype,"distributionPoint",void 0),Uu([ku({type:Qp,context:1,optional:!0,implicit:!0})],$p.prototype,"reasons",void 0),Uu([ku({type:ap,context:2,optional:!0,repeated:"sequence",implicit:!0})],$p.prototype,"cRLIssuer",void 0);let Gp=Hp=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Hp.prototype)}};var jp;Gp=Hp=Uu([Cu({type:Ll.Sequence,itemType:$p})],Gp);let qp=jp=class extends Gp{constructor(e){super(e),Object.setPrototypeOf(this,jp.prototype)}};qp=jp=Uu([Cu({type:Ll.Sequence,itemType:$p})],qp);class zp{constructor(e={}){this.onlyContainsUserCerts=zp.ONLY,this.onlyContainsCACerts=zp.ONLY,this.indirectCRL=zp.ONLY,this.onlyContainsAttributeCerts=zp.ONLY,Object.assign(this,e)}}var Wp;zp.ONLY=!1,Uu([ku({type:Fp,context:0,optional:!0})],zp.prototype,"distributionPoint",void 0),Uu([ku({type:Hl.Boolean,context:1,defaultValue:zp.ONLY,implicit:!0})],zp.prototype,"onlyContainsUserCerts",void 0),Uu([ku({type:Hl.Boolean,context:2,defaultValue:zp.ONLY,implicit:!0})],zp.prototype,"onlyContainsCACerts",void 0),Uu([ku({type:Qp,context:3,optional:!0,implicit:!0})],zp.prototype,"onlySomeReasons",void 0),Uu([ku({type:Hl.Boolean,context:4,defaultValue:zp.ONLY,implicit:!0})],zp.prototype,"indirectCRL",void 0),Uu([ku({type:Hl.Boolean,context:5,defaultValue:zp.ONLY,implicit:!0})],zp.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"}(Wp||(Wp={}));let Jp=class{constructor(e=Wp.unspecified){this.reason=Wp.unspecified,this.reason=e}toJSON(){return Wp[this.reason]}toString(){return this.toJSON()}};var Yp;Uu([ku({type:Hl.Enumerated})],Jp.prototype,"reason",void 0),Jp=Uu([Cu({type:Ll.Choice})],Jp);const Xp=`${gp}.37`;let Zp=Yp=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Yp.prototype)}};Zp=Yp=Uu([Cu({type:Ll.Sequence,itemType:Hl.ObjectIdentifier})],Zp);const eb=`${cp}.1`,tb=`${cp}.2`,rb=`${cp}.3`,sb=`${cp}.4`,ib=`${cp}.8`,nb=`${cp}.9`;let ab=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Uu([ku({type:Hl.Integer,converter:Xd})],ab.prototype,"value",void 0),ab=Uu([Cu({type:Ll.Choice})],ab);let ob=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var cb;Uu([ku({type:Hl.GeneralizedTime})],ob.prototype,"value",void 0),ob=Uu([Cu({type:Ll.Choice})],ob);let lb=cb=class extends Cp{constructor(e){super(e),Object.setPrototypeOf(this,cb.prototype)}};lb=cb=Uu([Cu({type:Ll.Sequence})],lb);const db=`${gp}.15`;var ub,hb;!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"}(ub||(ub={}));class fb extends qd{toJSON(){const e=this.toNumber(),t=[];return e&ub.cRLSign&&t.push("crlSign"),e&ub.dataEncipherment&&t.push("dataEncipherment"),e&ub.decipherOnly&&t.push("decipherOnly"),e&ub.digitalSignature&&t.push("digitalSignature"),e&ub.encipherOnly&&t.push("encipherOnly"),e&ub.keyAgreement&&t.push("keyAgreement"),e&ub.keyCertSign&&t.push("keyCertSign"),e&ub.keyEncipherment&&t.push("keyEncipherment"),e&ub.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class gb{constructor(e={}){this.base=new ap,this.minimum=0,Object.assign(this,e)}}Uu([ku({type:ap})],gb.prototype,"base",void 0),Uu([ku({type:Hl.Integer,context:0,defaultValue:0,implicit:!0})],gb.prototype,"minimum",void 0),Uu([ku({type:Hl.Integer,context:1,optional:!0,implicit:!0})],gb.prototype,"maximum",void 0);let pb=hb=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,hb.prototype)}};pb=hb=Uu([Cu({type:Ll.Sequence,itemType:gb})],pb);class bb{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:pb,context:0,optional:!0,implicit:!0})],bb.prototype,"permittedSubtrees",void 0),Uu([ku({type:pb,context:1,optional:!0,implicit:!0})],bb.prototype,"excludedSubtrees",void 0);class mb{constructor(e={}){Object.assign(this,e)}}var yb;Uu([ku({type:Hl.Integer,context:0,implicit:!0,optional:!0,converter:Xd})],mb.prototype,"requireExplicitPolicy",void 0),Uu([ku({type:Hl.Integer,context:1,implicit:!0,optional:!0,converter:Xd})],mb.prototype,"inhibitPolicyMapping",void 0);class Ab{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Ab.prototype,"issuerDomainPolicy",void 0),Uu([ku({type:Hl.ObjectIdentifier})],Ab.prototype,"subjectDomainPolicy",void 0);let Ib=yb=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,yb.prototype)}};var vb;Ib=yb=Uu([Cu({type:Ll.Sequence,itemType:Ab})],Ib);const wb=`${gp}.17`;let Sb=vb=class extends Cp{constructor(e){super(e),Object.setPrototypeOf(this,vb.prototype)}};Sb=vb=Uu([Cu({type:Ll.Sequence})],Sb);class Eb{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Cb;Uu([ku({type:Hl.ObjectIdentifier})],Eb.prototype,"type",void 0),Uu([ku({type:Hl.Any,repeated:"set"})],Eb.prototype,"values",void 0);let kb=Cb=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Cb.prototype)}};kb=Cb=Uu([Cu({type:Ll.Sequence,itemType:Eb})],kb);const xb=`${gp}.14`;class Bb extends Ip{}class _b{constructor(e={}){Object.assign(this,e)}}var Rb,Ob;Uu([ku({type:Hl.GeneralizedTime,context:0,implicit:!0,optional:!0})],_b.prototype,"notBefore",void 0),Uu([ku({type:Hl.GeneralizedTime,context:1,implicit:!0,optional:!0})],_b.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Rb||(Rb={}));class Ub extends qd{toJSON(){const e=[],t=this.toNumber();return t&Rb.pKIXCertificate&&e.push("pKIXCertificate"),t&Rb.newExtensions&&e.push("newExtensions"),t&Rb.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Tb{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Ub,Object.assign(this,e)}}Uu([ku({type:Hl.GeneralString})],Tb.prototype,"entrustVers",void 0),Uu([ku({type:Ub})],Tb.prototype,"entrustInfoFlags",void 0);let Nb=Ob=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Ob.prototype)}};Nb=Ob=Uu([Cu({type:Ll.Sequence,itemType:mp})],Nb);class Db{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof Db&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&vc(e.parameters,this.parameters)||e.parameters===this.parameters)}}Uu([ku({type:Hl.ObjectIdentifier})],Db.prototype,"algorithm",void 0),Uu([ku({type:Hl.Any,optional:!0})],Db.prototype,"parameters",void 0);class Mb{constructor(e={}){this.algorithm=new Db,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Db})],Mb.prototype,"algorithm",void 0),Uu([ku({type:Hl.BitString})],Mb.prototype,"subjectPublicKey",void 0);let Pb=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}};Uu([ku({type:Hl.UTCTime})],Pb.prototype,"utcTime",void 0),Uu([ku({type:Hl.GeneralizedTime})],Pb.prototype,"generalTime",void 0),Pb=Uu([Cu({type:Ll.Choice})],Pb);class Lb{constructor(e){this.notBefore=new Pb(new Date),this.notAfter=new Pb(new Date),e&&(this.notBefore=new Pb(e.notBefore),this.notAfter=new Pb(e.notAfter))}}var Hb;Uu([ku({type:Pb})],Lb.prototype,"notBefore",void 0),Uu([ku({type:Pb})],Lb.prototype,"notAfter",void 0);class Vb{constructor(e={}){this.extnID="",this.critical=Vb.CRITICAL,this.extnValue=new zd,Object.assign(this,e)}}Vb.CRITICAL=!1,Uu([ku({type:Hl.ObjectIdentifier})],Vb.prototype,"extnID",void 0),Uu([ku({type:Hl.Boolean,defaultValue:Vb.CRITICAL})],Vb.prototype,"critical",void 0),Uu([ku({type:zd})],Vb.prototype,"extnValue",void 0);let Kb=Hb=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Hb.prototype)}};var Qb;Kb=Hb=Uu([Cu({type:Ll.Sequence,itemType:Vb})],Kb),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(Qb||(Qb={}));class Fb{constructor(e={}){this.version=Qb.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new Db,this.issuer=new rp,this.validity=new Lb,this.subject=new rp,this.subjectPublicKeyInfo=new Mb,Object.assign(this,e)}}Uu([ku({type:Hl.Integer,context:0,defaultValue:Qb.v1})],Fb.prototype,"version",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],Fb.prototype,"serialNumber",void 0),Uu([ku({type:Db})],Fb.prototype,"signature",void 0),Uu([ku({type:rp})],Fb.prototype,"issuer",void 0),Uu([ku({type:Lb})],Fb.prototype,"validity",void 0),Uu([ku({type:rp})],Fb.prototype,"subject",void 0),Uu([ku({type:Mb})],Fb.prototype,"subjectPublicKeyInfo",void 0),Uu([ku({type:Hl.BitString,context:1,implicit:!0,optional:!0})],Fb.prototype,"issuerUniqueID",void 0),Uu([ku({type:Hl.BitString,context:2,implicit:!0,optional:!0})],Fb.prototype,"subjectUniqueID",void 0),Uu([ku({type:Kb,context:3,optional:!0})],Fb.prototype,"extensions",void 0);class $b{constructor(e={}){this.tbsCertificate=new Fb,this.signatureAlgorithm=new Db,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Fb})],$b.prototype,"tbsCertificate",void 0),Uu([ku({type:Db})],$b.prototype,"signatureAlgorithm",void 0),Uu([ku({type:Hl.BitString})],$b.prototype,"signatureValue",void 0);class Gb{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Pb,Object.assign(this,e)}}Uu([ku({type:Hl.Integer,converter:Xd})],Gb.prototype,"userCertificate",void 0),Uu([ku({type:Pb})],Gb.prototype,"revocationDate",void 0),Uu([ku({type:Vb,optional:!0,repeated:"sequence"})],Gb.prototype,"crlEntryExtensions",void 0);class jb{constructor(e={}){this.signature=new Db,this.issuer=new rp,this.thisUpdate=new Pb,Object.assign(this,e)}}Uu([ku({type:Hl.Integer,optional:!0})],jb.prototype,"version",void 0),Uu([ku({type:Db})],jb.prototype,"signature",void 0),Uu([ku({type:rp})],jb.prototype,"issuer",void 0),Uu([ku({type:Pb})],jb.prototype,"thisUpdate",void 0),Uu([ku({type:Pb,optional:!0})],jb.prototype,"nextUpdate",void 0),Uu([ku({type:Gb,repeated:"sequence",optional:!0})],jb.prototype,"revokedCertificates",void 0),Uu([ku({type:Vb,optional:!0,context:0,repeated:"sequence"})],jb.prototype,"crlExtensions",void 0);class qb{constructor(e={}){this.tbsCertList=new jb,this.signatureAlgorithm=new Db,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:jb})],qb.prototype,"tbsCertList",void 0),Uu([ku({type:Db})],qb.prototype,"signatureAlgorithm",void 0),Uu([ku({type:Hl.BitString})],qb.prototype,"signature",void 0);class zb{constructor(e={}){this.issuer=new rp,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:rp})],zb.prototype,"issuer",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],zb.prototype,"serialNumber",void 0);let Wb=class{constructor(e={}){Object.assign(this,e)}};var Jb;Uu([ku({type:Bb,context:0,implicit:!0})],Wb.prototype,"subjectKeyIdentifier",void 0),Uu([ku({type:zb})],Wb.prototype,"issuerAndSerialNumber",void 0),Wb=Uu([Cu({type:Ll.Choice})],Wb),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"}(Jb||(Jb={}));let Yb=class extends Db{};Yb=Uu([Cu({type:Ll.Sequence})],Yb);let Xb=class extends Db{};Xb=Uu([Cu({type:Ll.Sequence})],Xb);let Zb=class extends Db{};Zb=Uu([Cu({type:Ll.Sequence})],Zb);let em=class extends Db{};em=Uu([Cu({type:Ll.Sequence})],em);let tm=class extends Db{};tm=Uu([Cu({type:Ll.Sequence})],tm);let rm=class extends Db{};rm=Uu([Cu({type:Ll.Sequence})],rm);class sm{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var im;Uu([ku({type:Hl.ObjectIdentifier})],sm.prototype,"attrType",void 0),Uu([ku({type:Hl.Any,repeated:"set"})],sm.prototype,"attrValues",void 0);class nm{constructor(e={}){this.version=Jb.v0,this.sid=new Wb,this.digestAlgorithm=new Yb,this.signatureAlgorithm=new Xb,this.signature=new zd,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],nm.prototype,"version",void 0),Uu([ku({type:Wb})],nm.prototype,"sid",void 0),Uu([ku({type:Yb})],nm.prototype,"digestAlgorithm",void 0),Uu([ku({type:sm,repeated:"set",context:0,implicit:!0,optional:!0})],nm.prototype,"signedAttrs",void 0),Uu([ku({type:Xb})],nm.prototype,"signatureAlgorithm",void 0),Uu([ku({type:zd})],nm.prototype,"signature",void 0),Uu([ku({type:sm,repeated:"set",context:1,implicit:!0,optional:!0})],nm.prototype,"unsignedAttrs",void 0);let am=im=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,im.prototype)}};am=im=Uu([Cu({type:Ll.Set,itemType:nm})],am);let om=class extends Pb{};om=Uu([Cu({type:Ll.Choice})],om);let cm=class extends nm{};cm=Uu([Cu({type:Ll.Sequence})],cm);class lm{constructor(e={}){this.acIssuer=new ap,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var dm;Uu([ku({type:ap})],lm.prototype,"acIssuer",void 0),Uu([ku({type:Hl.Integer})],lm.prototype,"acSerial",void 0),Uu([ku({type:Eb,repeated:"sequence"})],lm.prototype,"attrs",void 0);let um=dm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,dm.prototype)}};um=dm=Uu([Cu({type:Ll.Sequence,itemType:Hl.ObjectIdentifier})],um);class hm{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Uu([ku({type:Hl.Integer,optional:!0})],hm.prototype,"pathLenConstraint",void 0),Uu([ku({type:um,implicit:!0,context:0,optional:!0})],hm.prototype,"permittedAttrs",void 0),Uu([ku({type:um,implicit:!0,context:1,optional:!0})],hm.prototype,"excludedAttrs",void 0),Uu([ku({type:Hl.Boolean,defaultValue:!0})],hm.prototype,"permitUnSpecified",void 0);class fm{constructor(e={}){this.issuer=new Cp,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var gm;Uu([ku({type:Cp})],fm.prototype,"issuer",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],fm.prototype,"serial",void 0),Uu([ku({type:Hl.BitString,optional:!0})],fm.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(gm||(gm={}));class pm{constructor(e={}){this.digestedObjectType=gm.publicKey,this.digestAlgorithm=new Db,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.Enumerated})],pm.prototype,"digestedObjectType",void 0),Uu([ku({type:Hl.ObjectIdentifier,optional:!0})],pm.prototype,"otherObjectTypeID",void 0),Uu([ku({type:Db})],pm.prototype,"digestAlgorithm",void 0),Uu([ku({type:Hl.BitString})],pm.prototype,"objectDigest",void 0);class bm{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:Cp,optional:!0})],bm.prototype,"issuerName",void 0),Uu([ku({type:fm,context:0,implicit:!0,optional:!0})],bm.prototype,"baseCertificateID",void 0),Uu([ku({type:pm,context:1,implicit:!0,optional:!0})],bm.prototype,"objectDigestInfo",void 0);let mm=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:ap,repeated:"sequence"})],mm.prototype,"v1Form",void 0),Uu([ku({type:bm,context:0,implicit:!0})],mm.prototype,"v2Form",void 0),mm=Uu([Cu({type:Ll.Choice})],mm);class ym{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Uu([ku({type:Hl.GeneralizedTime})],ym.prototype,"notBeforeTime",void 0),Uu([ku({type:Hl.GeneralizedTime})],ym.prototype,"notAfterTime",void 0);class Am{constructor(e={}){Object.assign(this,e)}}var Im,vm,wm;Uu([ku({type:fm,implicit:!0,context:0,optional:!0})],Am.prototype,"baseCertificateID",void 0),Uu([ku({type:Cp,implicit:!0,context:1,optional:!0})],Am.prototype,"entityName",void 0),Uu([ku({type:pm,implicit:!0,context:2,optional:!0})],Am.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(Im||(Im={}));class Sm{constructor(e={}){this.version=Im.v2,this.holder=new Am,this.issuer=new mm,this.signature=new Db,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new ym,this.attributes=[],Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],Sm.prototype,"version",void 0),Uu([ku({type:Am})],Sm.prototype,"holder",void 0),Uu([ku({type:mm})],Sm.prototype,"issuer",void 0),Uu([ku({type:Db})],Sm.prototype,"signature",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],Sm.prototype,"serialNumber",void 0),Uu([ku({type:ym})],Sm.prototype,"attrCertValidityPeriod",void 0),Uu([ku({type:Eb,repeated:"sequence"})],Sm.prototype,"attributes",void 0),Uu([ku({type:Hl.BitString,optional:!0})],Sm.prototype,"issuerUniqueID",void 0),Uu([ku({type:Kb,optional:!0})],Sm.prototype,"extensions",void 0);class Em{constructor(e={}){this.acinfo=new Sm,this.signatureAlgorithm=new Db,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Sm})],Em.prototype,"acinfo",void 0),Uu([ku({type:Db})],Em.prototype,"signatureAlgorithm",void 0),Uu([ku({type:Hl.BitString})],Em.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"}(vm||(vm={}));class Cm extends qd{}class km{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier,implicit:!0,context:0})],km.prototype,"type",void 0),Uu([ku({type:Hl.Any,implicit:!0,context:1})],km.prototype,"value",void 0);class xm{constructor(e={}){this.policyId="",this.classList=new Cm(vm.unclassified),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],xm.prototype,"policyId",void 0),Uu([ku({type:Cm,defaultValue:new Cm(vm.unclassified)})],xm.prototype,"classList",void 0),Uu([ku({type:km,repeated:"set"})],xm.prototype,"securityCategories",void 0);class Bm{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:zd})],Bm.prototype,"cotets",void 0),Uu([ku({type:Hl.ObjectIdentifier})],Bm.prototype,"oid",void 0),Uu([ku({type:Hl.Utf8String})],Bm.prototype,"string",void 0);class _m{constructor(e={}){this.values=[],Object.assign(this,e)}}Uu([ku({type:Cp,implicit:!0,context:0,optional:!0})],_m.prototype,"policyAuthority",void 0),Uu([ku({type:Bm,repeated:"sequence"})],_m.prototype,"values",void 0);class Rm{constructor(e={}){this.targetCertificate=new fm,Object.assign(this,e)}}Uu([ku({type:fm})],Rm.prototype,"targetCertificate",void 0),Uu([ku({type:ap,optional:!0})],Rm.prototype,"targetName",void 0),Uu([ku({type:pm,optional:!0})],Rm.prototype,"certDigestInfo",void 0);let Om=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:ap,context:0,implicit:!0})],Om.prototype,"targetName",void 0),Uu([ku({type:ap,context:1,implicit:!0})],Om.prototype,"targetGroup",void 0),Uu([ku({type:Rm,context:2,implicit:!0})],Om.prototype,"targetCert",void 0),Om=Uu([Cu({type:Ll.Choice})],Om);let Um=wm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,wm.prototype)}};var Tm;Um=wm=Uu([Cu({type:Ll.Sequence,itemType:Om})],Um);let Nm=Tm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Tm.prototype)}};Nm=Tm=Uu([Cu({type:Ll.Sequence,itemType:Um})],Nm);class Dm{constructor(e={}){Object.assign(this,e)}}Uu([ku({type:Cp,implicit:!0,context:0,optional:!0})],Dm.prototype,"roleAuthority",void 0),Uu([ku({type:ap,implicit:!0,context:1})],Dm.prototype,"roleName",void 0);class Mm{constructor(e={}){this.service=new ap,this.ident=new ap,Object.assign(this,e)}}var Pm;Uu([ku({type:ap})],Mm.prototype,"service",void 0),Uu([ku({type:ap})],Mm.prototype,"ident",void 0),Uu([ku({type:zd,optional:!0})],Mm.prototype,"authInfo",void 0);class Lm{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Lm.prototype,"otherCertFormat",void 0),Uu([ku({type:Hl.Any})],Lm.prototype,"otherCert",void 0);let Hm=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:$b})],Hm.prototype,"certificate",void 0),Uu([ku({type:Em,context:2,implicit:!0})],Hm.prototype,"v2AttrCert",void 0),Uu([ku({type:Lm,context:3,implicit:!0})],Hm.prototype,"other",void 0),Hm=Uu([Cu({type:Ll.Choice})],Hm);let Vm=Pm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Pm.prototype)}};Vm=Pm=Uu([Cu({type:Ll.Set,itemType:Hm})],Vm);class Km{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Km.prototype,"contentType",void 0),Uu([ku({type:Hl.Any,context:0})],Km.prototype,"content",void 0);let Qm=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:zd})],Qm.prototype,"single",void 0),Uu([ku({type:Hl.Any})],Qm.prototype,"any",void 0),Qm=Uu([Cu({type:Ll.Choice})],Qm);class Fm{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Fm.prototype,"eContentType",void 0),Uu([ku({type:Qm,context:0,optional:!0})],Fm.prototype,"eContent",void 0);let $m=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:zd,context:0,implicit:!0,optional:!0})],$m.prototype,"value",void 0),Uu([ku({type:zd,converter:su,context:0,implicit:!0,optional:!0,repeated:"sequence"})],$m.prototype,"constructedValue",void 0),$m=Uu([Cu({type:Ll.Choice})],$m);class Gm{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new em,Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],Gm.prototype,"contentType",void 0),Uu([ku({type:em})],Gm.prototype,"contentEncryptionAlgorithm",void 0),Uu([ku({type:$m,optional:!0})],Gm.prototype,"encryptedContent",void 0);class jm{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var qm;Uu([ku({type:Hl.ObjectIdentifier})],jm.prototype,"keyAttrId",void 0),Uu([ku({type:Hl.Any,optional:!0})],jm.prototype,"keyAttr",void 0);class zm{constructor(e={}){this.subjectKeyIdentifier=new Bb,Object.assign(this,e)}}Uu([ku({type:Bb})],zm.prototype,"subjectKeyIdentifier",void 0),Uu([ku({type:Hl.GeneralizedTime,optional:!0})],zm.prototype,"date",void 0),Uu([ku({type:jm,optional:!0})],zm.prototype,"other",void 0);let Wm=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:zm,context:0,implicit:!0,optional:!0})],Wm.prototype,"rKeyId",void 0),Uu([ku({type:zb,optional:!0})],Wm.prototype,"issuerAndSerialNumber",void 0),Wm=Uu([Cu({type:Ll.Choice})],Wm);class Jm{constructor(e={}){this.rid=new Wm,this.encryptedKey=new zd,Object.assign(this,e)}}Uu([ku({type:Wm})],Jm.prototype,"rid",void 0),Uu([ku({type:zd})],Jm.prototype,"encryptedKey",void 0);let Ym=qm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,qm.prototype)}};Ym=qm=Uu([Cu({type:Ll.Sequence,itemType:Jm})],Ym);class Xm{constructor(e={}){this.algorithm=new Db,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Db})],Xm.prototype,"algorithm",void 0),Uu([ku({type:Hl.BitString})],Xm.prototype,"publicKey",void 0);let Zm=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:Bb,context:0,implicit:!0,optional:!0})],Zm.prototype,"subjectKeyIdentifier",void 0),Uu([ku({type:Xm,context:1,implicit:!0,optional:!0})],Zm.prototype,"originatorKey",void 0),Uu([ku({type:zb,optional:!0})],Zm.prototype,"issuerAndSerialNumber",void 0),Zm=Uu([Cu({type:Ll.Choice})],Zm);class ey{constructor(e={}){this.version=Jb.v3,this.originator=new Zm,this.keyEncryptionAlgorithm=new Zb,this.recipientEncryptedKeys=new Ym,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],ey.prototype,"version",void 0),Uu([ku({type:Zm,context:0})],ey.prototype,"originator",void 0),Uu([ku({type:zd,context:1,optional:!0})],ey.prototype,"ukm",void 0),Uu([ku({type:Zb})],ey.prototype,"keyEncryptionAlgorithm",void 0),Uu([ku({type:Ym})],ey.prototype,"recipientEncryptedKeys",void 0);let ty=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:Bb,context:0,implicit:!0})],ty.prototype,"subjectKeyIdentifier",void 0),Uu([ku({type:zb})],ty.prototype,"issuerAndSerialNumber",void 0),ty=Uu([Cu({type:Ll.Choice})],ty);class ry{constructor(e={}){this.version=Jb.v0,this.rid=new ty,this.keyEncryptionAlgorithm=new Zb,this.encryptedKey=new zd,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],ry.prototype,"version",void 0),Uu([ku({type:ty})],ry.prototype,"rid",void 0),Uu([ku({type:Zb})],ry.prototype,"keyEncryptionAlgorithm",void 0),Uu([ku({type:zd})],ry.prototype,"encryptedKey",void 0);class sy{constructor(e={}){this.keyIdentifier=new zd,Object.assign(this,e)}}Uu([ku({type:zd})],sy.prototype,"keyIdentifier",void 0),Uu([ku({type:Hl.GeneralizedTime,optional:!0})],sy.prototype,"date",void 0),Uu([ku({type:jm,optional:!0})],sy.prototype,"other",void 0);class iy{constructor(e={}){this.version=Jb.v4,this.kekid=new sy,this.keyEncryptionAlgorithm=new Zb,this.encryptedKey=new zd,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],iy.prototype,"version",void 0),Uu([ku({type:sy})],iy.prototype,"kekid",void 0),Uu([ku({type:Zb})],iy.prototype,"keyEncryptionAlgorithm",void 0),Uu([ku({type:zd})],iy.prototype,"encryptedKey",void 0);class ny{constructor(e={}){this.version=Jb.v0,this.keyEncryptionAlgorithm=new Zb,this.encryptedKey=new zd,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],ny.prototype,"version",void 0),Uu([ku({type:rm,context:0,optional:!0})],ny.prototype,"keyDerivationAlgorithm",void 0),Uu([ku({type:Zb})],ny.prototype,"keyEncryptionAlgorithm",void 0),Uu([ku({type:zd})],ny.prototype,"encryptedKey",void 0);class ay{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],ay.prototype,"oriType",void 0),Uu([ku({type:Hl.Any})],ay.prototype,"oriValue",void 0);let oy=class{constructor(e={}){Object.assign(this,e)}};var cy;Uu([ku({type:ry,optional:!0})],oy.prototype,"ktri",void 0),Uu([ku({type:ey,context:1,implicit:!0,optional:!0})],oy.prototype,"kari",void 0),Uu([ku({type:iy,context:2,implicit:!0,optional:!0})],oy.prototype,"kekri",void 0),Uu([ku({type:ny,context:3,implicit:!0,optional:!0})],oy.prototype,"pwri",void 0),Uu([ku({type:ay,context:4,implicit:!0,optional:!0})],oy.prototype,"ori",void 0),oy=Uu([Cu({type:Ll.Choice})],oy);let ly=cy=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,cy.prototype)}};var dy;ly=cy=Uu([Cu({type:Ll.Set,itemType:oy})],ly);class uy{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],uy.prototype,"otherRevInfoFormat",void 0),Uu([ku({type:Hl.Any})],uy.prototype,"otherRevInfo",void 0);let hy=class{constructor(e={}){this.other=new uy,Object.assign(this,e)}};Uu([ku({type:uy,context:1,implicit:!0})],hy.prototype,"other",void 0),hy=Uu([Cu({type:Ll.Choice})],hy);let fy=dy=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,dy.prototype)}};fy=dy=Uu([Cu({type:Ll.Set,itemType:hy})],fy);class gy{constructor(e={}){Object.assign(this,e)}}var py;Uu([ku({type:Vm,context:0,implicit:!0,optional:!0})],gy.prototype,"certs",void 0),Uu([ku({type:fy,context:1,implicit:!0,optional:!0})],gy.prototype,"crls",void 0);let by=py=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,py.prototype)}};by=py=Uu([Cu({type:Ll.Set,itemType:sm})],by);class my{constructor(e={}){this.version=Jb.v0,this.recipientInfos=new ly,this.encryptedContentInfo=new Gm,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],my.prototype,"version",void 0),Uu([ku({type:gy,context:0,implicit:!0,optional:!0})],my.prototype,"originatorInfo",void 0),Uu([ku({type:ly})],my.prototype,"recipientInfos",void 0),Uu([ku({type:Gm})],my.prototype,"encryptedContentInfo",void 0),Uu([ku({type:by,context:1,implicit:!0,optional:!0})],my.prototype,"unprotectedAttrs",void 0);const yy="1.2.840.113549.1.7.2";var Ay;let Iy=Ay=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Ay.prototype)}};Iy=Ay=Uu([Cu({type:Ll.Set,itemType:Yb})],Iy);class vy{constructor(e={}){this.version=Jb.v0,this.digestAlgorithms=new Iy,this.encapContentInfo=new Fm,this.signerInfos=new am,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],vy.prototype,"version",void 0),Uu([ku({type:Iy})],vy.prototype,"digestAlgorithms",void 0),Uu([ku({type:Fm})],vy.prototype,"encapContentInfo",void 0),Uu([ku({type:Vm,context:0,implicit:!0,optional:!0})],vy.prototype,"certificates",void 0),Uu([ku({type:fy,context:1,implicit:!0,optional:!0})],vy.prototype,"crls",void 0),Uu([ku({type:am})],vy.prototype,"signerInfos",void 0);const wy="1.2.840.10045.2.1",Sy="1.2.840.10045.4.1",Ey="1.2.840.10045.4.3.1",Cy="1.2.840.10045.4.3.2",ky="1.2.840.10045.4.3.3",xy="1.2.840.10045.4.3.4",By="1.2.840.10045.3.1.7",_y="1.3.132.0.34",Ry="1.3.132.0.35";function Oy(e){return new Db({algorithm:e})}const Uy=Oy(Sy),Ty=(Oy(Ey),Oy(Cy)),Ny=Oy(ky),Dy=Oy(xy);let My=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:Hl.ObjectIdentifier})],My.prototype,"fieldType",void 0),Uu([ku({type:Hl.Any})],My.prototype,"parameters",void 0),My=Uu([Cu({type:Ll.Sequence})],My);let Py=class{constructor(e={}){Object.assign(this,e)}};var Ly;Uu([ku({type:Hl.OctetString})],Py.prototype,"a",void 0),Uu([ku({type:Hl.OctetString})],Py.prototype,"b",void 0),Uu([ku({type:Hl.BitString,optional:!0})],Py.prototype,"seed",void 0),Py=Uu([Cu({type:Ll.Sequence})],Py),function(e){e[e.ecpVer1=1]="ecpVer1"}(Ly||(Ly={}));let Hy=class{constructor(e={}){this.version=Ly.ecpVer1,Object.assign(this,e)}};Uu([ku({type:Hl.Integer})],Hy.prototype,"version",void 0),Uu([ku({type:My})],Hy.prototype,"fieldID",void 0),Uu([ku({type:Py})],Hy.prototype,"curve",void 0),Uu([ku({type:class extends zd{}})],Hy.prototype,"base",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],Hy.prototype,"order",void 0),Uu([ku({type:Hl.Integer,optional:!0})],Hy.prototype,"cofactor",void 0),Hy=Uu([Cu({type:Ll.Sequence})],Hy);let Vy=class{constructor(e={}){Object.assign(this,e)}};Uu([ku({type:Hl.ObjectIdentifier})],Vy.prototype,"namedCurve",void 0),Uu([ku({type:Hl.Null})],Vy.prototype,"implicitCurve",void 0),Uu([ku({type:Hy})],Vy.prototype,"specifiedCurve",void 0),Vy=Uu([Cu({type:Ll.Choice})],Vy);class Ky{constructor(e={}){this.version=1,this.privateKey=new zd,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],Ky.prototype,"version",void 0),Uu([ku({type:zd})],Ky.prototype,"privateKey",void 0),Uu([ku({type:Vy,context:0,optional:!0})],Ky.prototype,"parameters",void 0),Uu([ku({type:Hl.BitString,context:1,optional:!0})],Ky.prototype,"publicKey",void 0);class Qy{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.Integer,converter:Xd})],Qy.prototype,"r",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],Qy.prototype,"s",void 0);const Fy="1.2.840.113549.1.1",$y=`${Fy}.1`,Gy=`${Fy}.7`,jy=`${Fy}.9`,qy=`${Fy}.10`,zy=`${Fy}.2`,Wy=`${Fy}.4`,Jy=`${Fy}.5`,Yy=`${Fy}.14`,Xy=`${Fy}.11`,Zy=`${Fy}.12`,eA=`${Fy}.13`,tA=`${Fy}.15`,rA=`${Fy}.16`,sA="1.3.14.3.2.26",iA="2.16.840.1.101.3.4.2.4",nA="2.16.840.1.101.3.4.2.1",aA="2.16.840.1.101.3.4.2.2",oA="2.16.840.1.101.3.4.2.3",cA=`${Fy}.8`;function lA(e){return new Db({algorithm:e,parameters:null})}lA("1.2.840.113549.2.2"),lA("1.2.840.113549.2.5");const dA=lA(sA),uA=(lA(iA),lA(nA),lA(aA),lA(oA),lA("2.16.840.1.101.3.4.2.5"),lA("2.16.840.1.101.3.4.2.6"),new Db({algorithm:cA,parameters:Ou.serialize(dA)})),hA=new Db({algorithm:jy,parameters:Ou.serialize(ru.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});lA($y),lA(zy),lA(Wy),lA(Jy),lA(tA),lA(rA),lA(Zy),lA(eA),lA(tA),lA(rA);class fA{constructor(e={}){this.hashAlgorithm=new Db(dA),this.maskGenAlgorithm=new Db({algorithm:cA,parameters:Ou.serialize(dA)}),this.pSourceAlgorithm=new Db(hA),Object.assign(this,e)}}Uu([ku({type:Db,context:0,defaultValue:dA})],fA.prototype,"hashAlgorithm",void 0),Uu([ku({type:Db,context:1,defaultValue:uA})],fA.prototype,"maskGenAlgorithm",void 0),Uu([ku({type:Db,context:2,defaultValue:hA})],fA.prototype,"pSourceAlgorithm",void 0),new Db({algorithm:Gy,parameters:Ou.serialize(new fA)});class gA{constructor(e={}){this.hashAlgorithm=new Db(dA),this.maskGenAlgorithm=new Db({algorithm:cA,parameters:Ou.serialize(dA)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Uu([ku({type:Db,context:0,defaultValue:dA})],gA.prototype,"hashAlgorithm",void 0),Uu([ku({type:Db,context:1,defaultValue:uA})],gA.prototype,"maskGenAlgorithm",void 0),Uu([ku({type:Hl.Integer,context:2,defaultValue:20})],gA.prototype,"saltLength",void 0),Uu([ku({type:Hl.Integer,context:3,defaultValue:1})],gA.prototype,"trailerField",void 0),new Db({algorithm:qy,parameters:Ou.serialize(new gA)});class pA{constructor(e={}){this.digestAlgorithm=new Db,this.digest=new zd,Object.assign(this,e)}}var bA;Uu([ku({type:Db})],pA.prototype,"digestAlgorithm",void 0),Uu([ku({type:zd})],pA.prototype,"digest",void 0);class mA{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.Integer,converter:Xd})],mA.prototype,"prime",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],mA.prototype,"exponent",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],mA.prototype,"coefficient",void 0);let yA=bA=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,bA.prototype)}};yA=bA=Uu([Cu({type:Ll.Sequence,itemType:mA})],yA);class AA{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)}}Uu([ku({type:Hl.Integer})],AA.prototype,"version",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"modulus",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"publicExponent",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"privateExponent",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"prime1",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"prime2",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"exponent1",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"exponent2",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],AA.prototype,"coefficient",void 0),Uu([ku({type:yA,optional:!0})],AA.prototype,"otherPrimeInfos",void 0);class IA{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var vA;Uu([ku({type:Hl.Integer,converter:Xd})],IA.prototype,"modulus",void 0),Uu([ku({type:Hl.Integer,converter:Xd})],IA.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"}(vA||(vA={}));const wA=vA;var SA=function(e,t){return SA=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])},SA(e,t)};function EA(e,t){function r(){this.constructor=e}SA(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function CA(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 kA(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)a.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 a}function xA(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(kA(arguments[t]));return e}function BA(e){return!!e.useClass}function _A(e){return!!e.useFactory}var RA=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,xA(t))}}),t},e}();function OA(e){return"string"==typeof e||"symbol"==typeof e}function UA(e){return"object"==typeof e&&"token"in e&&"transform"in e}function TA(e){return!!e.useToken}function NA(e){return null!=e.useValue}var DA=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 MA=DA,PA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return EA(t,e),t}(MA),LA=function(){this.scopedResolutions=new Map};var HA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return EA(t,e),t}(MA),VA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return EA(t,e),t}(MA);const KA=function(){this.preResolution=new HA,this.postResolution=new VA};var QA=new Map,FA=function(){function e(e){this.parent=e,this._registry=new PA,this.interceptors=new KA,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:wA.Transient}),this.ensureNotDisposed(),s=function(e){return BA(e)||NA(e)||TA(e)||_A(e)}(t)?t:{useClass:t},TA(s))for(var i=[e],n=s;null!=n;){var a=n.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+xA(i,[a]).join(" -> "));i.push(a);var o=this._registry.get(a);n=o&&TA(o.provider)?o.provider:null}if((r.lifecycle===wA.Singleton||r.lifecycle==wA.ContainerScoped||r.lifecycle==wA.ResolutionScoped)&&(NA(s)||_A(s)))throw new Error('Cannot use lifecycle "'+wA[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(),OA(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(),OA(e)){if(OA(t))return this.register(e,{useToken:t},{lifecycle:wA.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:wA.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!OA(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:wA.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new LA),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&OA(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 RA}(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=CA(this.interceptors.preResolution.getAll(e)),a=n.next();!a.done;a=n.next()){var o=a.value;"Once"!=o.options.frequency&&i.push(o),o.callback(e,t)}}catch(e){r={error:e}}finally{try{a&&!a.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 a=CA(this.interceptors.postResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var c=o.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===wA.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===wA.Singleton,i=e.options.lifecycle===wA.ContainerScoped,n=s||i;return r=NA(e.provider)?e.provider.useValue:TA(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):BA(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):_A(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===wA.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new LA),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&OA(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 a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},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=CA(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=kA(s.value,2),n=i[0],a=i[1];this._registry.setAll(n,a.filter(function(e){return!NA(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=CA(this._registry.entries()),n=i.next();!n.done;n=i.next()){var a=kA(n.value,2),o=a[0],c=a[1];c.some(function(e){return e.options.lifecycle===wA.ContainerScoped})&&s._registry.setAll(o,c.map(function(e){return e.options.lifecycle===wA.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 a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(n){return function(o){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)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 a.label++,{value:n[1],done:!1};case 5:a.label++,s=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){a.label=n[1];break}if(6===n[0]&&a.label<i[1]){a.label=i[1],i=n;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(n);break}i[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}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,o])}}}(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 RA)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=QA.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,xA([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,a,o,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?UA(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,xA([r.resolveAll(s.token,new LA,s.isOptional)],s.transformArgs)):(a=r.resolve(s.transform)).transform.apply(a,xA([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new LA,s.isOptional):r.resolve(s.token,e,s.isOptional):UA(s)?(o=r.resolve(s.transform,e)).transform.apply(o,xA([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=kA(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),xA([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}(),$A=new FA;const GA=function(e){return function(t){QA.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){$A.register(e,t)}):$A.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 jA;class qA{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Uu([ku({type:Hl.ObjectIdentifier})],qA.prototype,"attrId",void 0),Uu([ku({type:Hl.Any,repeated:"set"})],qA.prototype,"attrValues",void 0);let zA=jA=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,jA.prototype)}};var WA;zA=jA=Uu([Cu({type:Ll.Sequence,itemType:qA})],zA);let JA=WA=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,WA.prototype)}};JA=WA=Uu([Cu({type:Ll.Sequence,itemType:Km})],JA);class YA{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],YA.prototype,"certId",void 0),Uu([ku({type:Hl.Any,context:0})],YA.prototype,"certValue",void 0);class XA{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],XA.prototype,"crlId",void 0),Uu([ku({type:Hl.Any,context:0})],XA.prototype,"crltValue",void 0);class ZA extends zd{}class eI{constructor(e={}){this.encryptionAlgorithm=new Db,this.encryptedData=new ZA,Object.assign(this,e)}}var tI,rI;Uu([ku({type:Db})],eI.prototype,"encryptionAlgorithm",void 0),Uu([ku({type:ZA})],eI.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(rI||(rI={}));class sI extends zd{}let iI=tI=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,tI.prototype)}};iI=tI=Uu([Cu({type:Ll.Sequence,itemType:Eb})],iI);class nI{constructor(e={}){this.version=rI.v1,this.privateKeyAlgorithm=new Db,this.privateKey=new sI,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],nI.prototype,"version",void 0),Uu([ku({type:Db})],nI.prototype,"privateKeyAlgorithm",void 0),Uu([ku({type:sI})],nI.prototype,"privateKey",void 0),Uu([ku({type:iI,implicit:!0,context:0,optional:!0})],nI.prototype,"attributes",void 0);let aI=class extends nI{};aI=Uu([Cu({type:Ll.Sequence})],aI);let oI=class extends eI{};oI=Uu([Cu({type:Ll.Sequence})],oI);class cI{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],cI.prototype,"secretTypeId",void 0),Uu([ku({type:Hl.Any,context:0})],cI.prototype,"secretValue",void 0);class lI{constructor(e={}){this.mac=new pA,this.macSalt=new zd,this.iterations=1,Object.assign(this,e)}}Uu([ku({type:pA})],lI.prototype,"mac",void 0),Uu([ku({type:zd})],lI.prototype,"macSalt",void 0),Uu([ku({type:Hl.Integer,defaultValue:1})],lI.prototype,"iterations",void 0);class dI{constructor(e={}){this.version=3,this.authSafe=new Km,this.macData=new lI,Object.assign(this,e)}}var uI;Uu([ku({type:Hl.Integer})],dI.prototype,"version",void 0),Uu([ku({type:Km})],dI.prototype,"authSafe",void 0),Uu([ku({type:lI,optional:!0})],dI.prototype,"macData",void 0);class hI{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:Hl.ObjectIdentifier})],hI.prototype,"bagId",void 0),Uu([ku({type:Hl.Any,context:0})],hI.prototype,"bagValue",void 0),Uu([ku({type:qA,repeated:"set",optional:!0})],hI.prototype,"bagAttributes",void 0);let fI=uI=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,uI.prototype)}};var gI,pI,bI;fI=uI=Uu([Cu({type:Ll.Sequence,itemType:hI})],fI);const mI="1.2.840.113549.1.9",yI=`${mI}.7`,AI=`${mI}.14`;let II=class extends Yg{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Uu([ku({type:Hl.IA5String})],II.prototype,"ia5String",void 0),II=Uu([Cu({type:Ll.Choice})],II);let vI=class extends Km{};vI=Uu([Cu({type:Ll.Sequence})],vI);let wI=class extends dI{};wI=Uu([Cu({type:Ll.Sequence})],wI);let SI=class extends eI{};SI=Uu([Cu({type:Ll.Sequence})],SI);let EI=class{constructor(e=""){this.value=e}toString(){return this.value}};Uu([ku({type:Hl.IA5String})],EI.prototype,"value",void 0),EI=Uu([Cu({type:Ll.Choice})],EI);let CI=class extends II{};CI=Uu([Cu({type:Ll.Choice})],CI);let kI=class extends Yg{};kI=Uu([Cu({type:Ll.Choice})],kI);let xI=class{constructor(e=new Date){this.value=e}};Uu([ku({type:Hl.GeneralizedTime})],xI.prototype,"value",void 0),xI=Uu([Cu({type:Ll.Choice})],xI);let BI=class extends Yg{};BI=Uu([Cu({type:Ll.Choice})],BI);let _I=class{constructor(e="M"){this.value=e}toString(){return this.value}};Uu([ku({type:Hl.PrintableString})],_I.prototype,"value",void 0),_I=Uu([Cu({type:Ll.Choice})],_I);let RI=class{constructor(e=""){this.value=e}toString(){return this.value}};Uu([ku({type:Hl.PrintableString})],RI.prototype,"value",void 0),RI=Uu([Cu({type:Ll.Choice})],RI);let OI=class extends RI{};OI=Uu([Cu({type:Ll.Choice})],OI);let UI=class extends Yg{};UI=Uu([Cu({type:Ll.Choice})],UI);let TI=class{constructor(e=""){this.value=e}toString(){return this.value}};Uu([ku({type:Hl.ObjectIdentifier})],TI.prototype,"value",void 0),TI=Uu([Cu({type:Ll.Choice})],TI);let NI=class extends Pb{};NI=Uu([Cu({type:Ll.Choice})],NI);let DI=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Uu([ku({type:Hl.Integer})],DI.prototype,"value",void 0),DI=Uu([Cu({type:Ll.Choice})],DI);let MI=class extends nm{};MI=Uu([Cu({type:Ll.Sequence})],MI);let PI=class extends Yg{};PI=Uu([Cu({type:Ll.Choice})],PI);let LI=gI=class extends Kb{constructor(e){super(e),Object.setPrototypeOf(this,gI.prototype)}};LI=gI=Uu([Cu({type:Ll.Sequence})],LI);let HI=pI=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,pI.prototype)}};HI=pI=Uu([Cu({type:Ll.Set,itemType:sm})],HI);let VI=class{constructor(e=""){this.value=e}toString(){return this.value}};Uu([ku({type:Hl.BmpString})],VI.prototype,"value",void 0),VI=Uu([Cu({type:Ll.Choice})],VI);let KI=class extends Db{};KI=Uu([Cu({type:Ll.Sequence})],KI);let QI=bI=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,bI.prototype)}};var FI;QI=bI=Uu([Cu({type:Ll.Sequence,itemType:KI})],QI);let $I=FI=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,FI.prototype)}};$I=FI=Uu([Cu({type:Ll.Sequence,itemType:Eb})],$I);class GI{constructor(e={}){this.version=0,this.subject=new rp,this.subjectPKInfo=new Mb,this.attributes=new $I,Object.assign(this,e)}}Uu([ku({type:Hl.Integer})],GI.prototype,"version",void 0),Uu([ku({type:rp})],GI.prototype,"subject",void 0),Uu([ku({type:Mb})],GI.prototype,"subjectPKInfo",void 0),Uu([ku({type:$I,implicit:!0,context:0})],GI.prototype,"attributes",void 0);class jI{constructor(e={}){this.certificationRequestInfo=new GI,this.signatureAlgorithm=new Db,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Uu([ku({type:GI})],jI.prototype,"certificationRequestInfo",void 0),Uu([ku({type:Db})],jI.prototype,"signatureAlgorithm",void 0),Uu([ku({type:Hl.BitString})],jI.prototype,"signature",void 0);const qI="crypto.algorithm",zI="crypto.algorithmProvider";var WI;$A.registerSingleton(zI,class{getAlgorithms(){return $A.resolveAll(qI)}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 Db({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 JI="1.3.36.3.3.2.8.1.1",YI=`${JI}.1`,XI=`${JI}.2`,ZI=`${JI}.3`,ev=`${JI}.4`,tv=`${JI}.5`,rv=`${JI}.6`,sv=`${JI}.7`,iv=`${JI}.8`,nv=`${JI}.9`,av=`${JI}.10`,ov=`${JI}.11`,cv=`${JI}.12`,lv=`${JI}.13`,dv=`${JI}.14`,uv="brainpoolP160r1",hv="brainpoolP160t1",fv="brainpoolP192r1",gv="brainpoolP192t1",pv="brainpoolP224r1",bv="brainpoolP224t1",mv="brainpoolP256r1",yv="brainpoolP256t1",Av="brainpoolP320r1",Iv="brainpoolP320t1",vv="brainpoolP384r1",wv="brainpoolP384t1",Sv="brainpoolP512r1",Ev="brainpoolP512t1",Cv="ECDSA";let kv=WI=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Cv.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Uy;case"sha-256":return Ty;case"sha-384":return Ny;case"sha-512":return Dy}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=By;break;case"K-256":t=WI.SECP256K1;break;case"P-384":t=_y;break;case"P-521":t=Ry;break;case uv:t=YI;break;case hv:t=XI;break;case fv:t=ZI;break;case gv:t=ev;break;case pv:t=tv;break;case bv:t=rv;break;case mv:t=sv;break;case yv:t=iv;break;case Av:t=nv;break;case Iv:t=av;break;case vv:t=ov;break;case wv:t=cv;break;case Sv:t=lv;break;case Ev:t=dv}if(t)return new Db({algorithm:wy,parameters:Ou.serialize(new Vy({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case Sy:return{name:Cv,hash:{name:"SHA-1"}};case Cy:return{name:Cv,hash:{name:"SHA-256"}};case ky:return{name:Cv,hash:{name:"SHA-384"}};case xy:return{name:Cv,hash:{name:"SHA-512"}};case wy:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Ou.parse(e.parameters,Vy).namedCurve){case By:return{name:Cv,namedCurve:"P-256"};case WI.SECP256K1:return{name:Cv,namedCurve:"K-256"};case _y:return{name:Cv,namedCurve:"P-384"};case Ry:return{name:Cv,namedCurve:"P-521"};case YI:return{name:Cv,namedCurve:uv};case XI:return{name:Cv,namedCurve:hv};case ZI:return{name:Cv,namedCurve:fv};case ev:return{name:Cv,namedCurve:gv};case tv:return{name:Cv,namedCurve:pv};case rv:return{name:Cv,namedCurve:bv};case sv:return{name:Cv,namedCurve:mv};case iv:return{name:Cv,namedCurve:yv};case nv:return{name:Cv,namedCurve:Av};case av:return{name:Cv,namedCurve:Iv};case ov:return{name:Cv,namedCurve:vv};case cv:return{name:Cv,namedCurve:wv};case lv:return{name:Cv,namedCurve:Sv};case dv:return{name:Cv,namedCurve:Ev}}}return null}};kv.SECP256K1="1.3.132.0.10",kv=WI=Uu([GA()],kv),$A.registerSingleton(qI,kv);const xv=Symbol("name"),Bv=Symbol("value");class _v{constructor(e,t={},r=""){this[xv]=e,this[Bv]=r;for(const e in t)this[e]=t[e]}}_v.NAME=xv,_v.VALUE=Bv;class Rv{static toString(e){return this.items[e]||e}}Rv.items={[sA]:"sha1",[iA]:"sha224",[nA]:"sha256",[aA]:"sha384",[oA]:"sha512",[$y]:"rsaEncryption",[Jy]:"sha1WithRSAEncryption",[Yy]:"sha224WithRSAEncryption",[Xy]:"sha256WithRSAEncryption",[Zy]:"sha384WithRSAEncryption",[eA]:"sha512WithRSAEncryption",[wy]:"ecPublicKey",[Sy]:"ecdsaWithSHA1",[Ey]:"ecdsaWithSHA224",[Cy]:"ecdsaWithSHA256",[ky]:"ecdsaWithSHA384",[xy]:"ecdsaWithSHA512",[eb]:"TLS WWW server authentication",[tb]:"TLS WWW client authentication",[rb]:"Code Signing",[sb]:"E-mail Protection",[ib]:"Time Stamping",[nb]:"OCSP Signing",[yy]:"Signed Data"};class Ov{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[_v.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[_v.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],a=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${a}${n}`);else if(n instanceof Date)r.push(`${s}${a}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[_v.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof _v)n[_v.NAME]=i,r.push(...this.serializeObj(n,t));else if(hc.isBufferSource(n))i?(r.push(`${s}${a}`),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[_v.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=hc.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)}}Ov.oidSerializer=Rv,Ov.algorithmSerializer=class{static toTextObject(e){const t=new _v("Algorithm Identifier",{},Rv.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case wy:{const r=(new kv).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Uv{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Ou.serialize(t),this.onInit(t)}else{const t=Ou.parse(e[0],e[1]);this.rawData=hc.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Uv&&vc(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Ou.toString(this.rawData);case"text":return Ov.serialize(this.toTextObject());case"hex":return Ac.ToHex(this.rawData);case"base64":return Ac.ToBase64(this.rawData);case"base64url":return Ac.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 _v(this.getTextName(),{},e)}}Uv.NAME="ASN";class Tv extends Uv{constructor(...e){let t;t=hc.isBufferSource(e[0])?hc.toArrayBuffer(e[0]):Ou.serialize(new Vb({extnID:e[0],critical:e[1],extnValue:new zd(hc.toArrayBuffer(e[2]))})),super(t,Vb)}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[_v.NAME]===Tv.NAME&&(e[_v.NAME]=Rv.toString(this.type)),e}}var Nv;class Dv{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[Nv]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(Dv.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(Dv.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=Dv.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(Dv.DEFAULT,e);return this}}Nv=Symbol.toStringTag,Dv.DEFAULT="default";const Mv=new Dv,Pv=/^[0-2](?:\.[1-9][0-9]*)+$/;class Lv{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(Pv).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const Hv=new Lv;function Vv(e,t){return`\\${Ac.ToHex(Ac.FromUtf8String(t)).toUpperCase()}`}Hv.register("CN","2.5.4.3"),Hv.register("L","2.5.4.7"),Hv.register("ST","2.5.4.8"),Hv.register("O","2.5.4.10"),Hv.register("OU","2.5.4.11"),Hv.register("C","2.5.4.6"),Hv.register("DC","0.9.2342.19200300.100.1.25"),Hv.register("E","1.2.840.113549.1.9.1"),Hv.register("G","2.5.4.42"),Hv.register("I","2.5.4.43"),Hv.register("SN","2.5.4.4"),Hv.register("T","2.5.4.12");class Kv{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 Lv,this.asn=new rp;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 rp?this.asn=e:hc.isBufferSource(e)?this.asn=Ou.parse(e,rp):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||Hv.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)||Hv.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Ac.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Vv)}`).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?`#${Ac.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new rp,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 a=s[3];e=this.getTypeOid(e);const o=this.createAttribute(e,r);"+"===i?t[t.length-1].push(o):t.push(new ep([o])),i=a}return t}fromJSON(e){const t=new rp;for(const r of e){const e=new ep;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 Zg({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=Ac.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:Kv.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 Ou.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]||Mv.get()):r=e[0]||Mv.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const Qv="Cannot initialize GeneralName from ASN.1 data.",Fv=`${Qv} Unsupported string format in use.`,$v=`${Qv} Value doesn't match to GUID regular expression.`,Gv=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,jv="1.3.6.1.4.1.311.25.1",qv="1.3.6.1.4.1.311.20.2.3",zv="dns",Wv="dn",Jv="email",Yv="ip",Xv="url",Zv="guid",ew="upn",tw="id";class rw extends Uv{constructor(...e){let t;if(2===e.length)switch(e[0]){case Wv:{const r=new Kv(e[1]).toArrayBuffer(),s=Ou.parse(r,rp);t=new ap({directoryName:s});break}case zv:t=new ap({dNSName:e[1]});break;case Jv:t=new ap({rfc822Name:e[1]});break;case Zv:{const r=new RegExp(Gv,"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?Ac.ToHex(new Uint8Array(Ac.FromHex(e)).reverse()):e).join("");t=new ap({otherName:new ip({typeId:jv,value:Ou.serialize(new zd(Ac.FromHex(s)))})});break}case Yv:t=new ap({iPAddress:e[1]});break;case tw:t=new ap({registeredID:e[1]});break;case ew:t=new ap({otherName:new ip({typeId:qv,value:Ou.serialize(nu.toASN(e[1]))})});break;case Xv:t=new ap({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=hc.isBufferSource(e[0])?Ou.parse(e[0],ap):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=zv,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=Jv,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=Yv,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=Xv,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=tw,this.value=e.registeredID;else if(null!=e.directoryName)this.type=Wv,this.value=new Kv(e.directoryName).toString();else{if(null==e.otherName)throw new Error(Fv);if(e.otherName.typeId===jv){this.type=Zv;const t=Ou.parse(e.otherName.value,zd),r=new RegExp(Gv,"i").exec(Ac.ToHex(t));if(!r)throw new Error($v);this.value=r.slice(1).map((e,t)=>t<3?Ac.ToHex(new Uint8Array(Ac.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==qv)throw new Error(Fv);this.type=ew,this.value=Ou.parse(e.otherName.value,Yg).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Wv:case zv:case Zv:case Yv:case tw:case ew:case Xv:e=this.type.toUpperCase();break;case Jv:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===tw&&(t=Rv.toString(t)),new _v(e,void 0,t)}}class sw extends Uv{constructor(e){let t;if(e instanceof Cp)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof ap)r.push(t);else{const e=Ou.parse(new rw(t.type,t.value).rawData,ap);r.push(e)}t=new Cp(r)}else{if(!hc.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Ou.parse(e,Cp)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new rw(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[_v.NAME]];Array.isArray(s)||(s=[],e[r[_v.NAME]]=s),s.push(r)}return e}}sw.NAME="GeneralNames";const iw="-{5}",nw="\\n",aw="\\n",ow=`${iw}BEGIN ([^${nw}]+(?=${iw}))${iw}${aw}(?:((?:[^:${nw}]+: (?:[^${nw}]+${aw}(?: +[^${nw}]+${aw})*))+))?${aw}?((?:[a-zA-Z0-9=+/]+${aw})+)${iw}END \\1${iw}`;class cw{static isPem(e){return"string"==typeof e&&new RegExp(ow,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(ow,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${nw}]+`,"g"),""),t={type:s[1],headers:[],rawData:Ac.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(aw,"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(!hc.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:hc.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:hc.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=Ac.ToBase64(e.rawData);let n,a=0;const o=Array();for(;a<i.length&&(i.length-a<64?n=i.substring(a):(n=i.substring(a,a+64),a+=64),0!==n.length)&&(o.push(n),!(n.length<64)););return s.push(...o),s.push(`-----END ${r}-----`),s.join("\n")}}cw.CertificateTag="CERTIFICATE",cw.CrlTag="CRL",cw.CertificateRequestTag="CERTIFICATE REQUEST",cw.PublicKeyTag="PUBLIC KEY",cw.PrivateKeyTag="PRIVATE KEY";class lw extends Uv{static isAsnEncoded(e){return hc.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(cw.isPem(e))return cw.decode(e)[0];if(Ac.isHex(e))return Ac.FromHex(e);if(Ac.isBase64(e))return Ac.FromBase64(e);if(Ac.isBase64Url(e))return Ac.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Ac.ToBinary(e);return cw.isPem(t)?cw.decode(t)[0]:Ac.isHex(t)?Ac.FromHex(t):Ac.isBase64(t)?Ac.FromBase64(t):Ac.isBase64Url(t)?Ac.FromBase64Url(t):hc.toArrayBuffer(e)}}constructor(...e){lw.isAsnEncoded(e[0])?super(lw.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?cw.encode(this.rawData,this.tag):super.toString(e)}}class dw extends lw{static async create(e,t=Mv.get()){if(e instanceof dw)return e;if(Dv.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new dw(r)}if(e.publicKey)return e.publicKey;if(hc.isBufferSource(e))return new dw(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){lw.isAsnEncoded(e)?super(e,Mb):super(e),this.tag=cw.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]||Mv.get()):t=e[0]||Mv.get();let i=this.rawData;const n=Ou.parse(this.rawData,Mb);return n.algorithm.algorithm===qy&&(i=function(e){return e.algorithm=new Db({algorithm:$y,parameters:null}),Ou.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=$A.resolve(zI),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case $y:{const t=Ou.parse(e.subjectPublicKey,IA),s=hc.toUint8Array(t.modulus);r.publicExponent=hc.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]||Mv.get()):r=e[0]||Mv.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=Mv.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=Mv.get();const s=Ou.parse(this.rawData,Mb);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Ou.parse(this.rawData,Mb);return e.Algorithm=Ov.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===wy?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class uw extends Tv{static async create(e,t=!1,r=Mv.get()){if("name"in e&&"serialNumber"in e)return new uw(e,t);const s=await dw.create(e,r),i=await s.getKeyIdentifier(r);return new uw(Ac.ToHex(i),t)}constructor(...e){if(hc.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new vp({keyIdentifier:new Ip(Ac.FromHex(e[0]))});super(Ap,e[1],Ou.serialize(t))}else{const t=e[0],r=t.name instanceof sw?Ou.parse(t.name.rawData,Cp):t.name,s=new vp({authorityCertIssuer:r,authorityCertSerialNumber:Ac.FromHex(t.serialNumber)});super(Ap,e[1],Ou.serialize(s))}}onInit(e){super.onInit(e);const t=Ou.parse(e.extnValue,vp);t.keyIdentifier&&(this.keyId=Ac.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Ac.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ou.parse(this.value,vp);return t.authorityCertIssuer&&(e["Authority Issuer"]=new sw(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}uw.NAME="Authority Key Identifier";class hw extends Tv{constructor(...e){if(hc.isBufferSource(e[0])){super(e[0]);const t=Ou.parse(this.value,Sp);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Sp({cA:e[0],pathLenConstraint:e[1]});super(wp,e[2],Ou.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 fw,gw;hw.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"}(fw||(fw={}));class pw extends Tv{constructor(...e){if(hc.isBufferSource(e[0])){super(e[0]);const t=Ou.parse(this.value,Zp);this.usages=t.map(e=>e)}else{const t=new Zp(e[0]);super(Xp,e[1],Ou.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Rv.toString(e)).join(", "),e}}pw.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"}(gw||(gw={}));class bw extends Tv{constructor(...e){if(hc.isBufferSource(e[0])){super(e[0]);const t=Ou.parse(this.value,fb);this.usages=t.toNumber()}else{const t=new fb(e[0]);super(db,e[1],Ou.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ou.parse(this.value,fb);return e[""]=t.toJSON().join(", "),e}}bw.NAME="Key Usages";class mw extends Tv{static async create(e,t=!1,r=Mv.get()){const s=await dw.create(e,r),i=await s.getKeyIdentifier(r);return new mw(Ac.ToHex(i),t)}constructor(...e){if(hc.isBufferSource(e[0])){super(e[0]);const t=Ou.parse(this.value,Bb);this.keyId=Ac.ToHex(t)}else{const t="string"==typeof e[0]?Ac.FromHex(e[0]):e[0],r=new Bb(t);super(xb,e[1],Ou.serialize(r)),this.keyId=Ac.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Ou.parse(this.value,Bb);return e[""]=t,e}}mw.NAME="Subject Key Identifier";class yw extends Tv{constructor(...e){hc.isBufferSource(e[0])?super(e[0]):super(wb,e[1],new sw(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Ou.parse(e.extnValue,Sb);this.names=new sw(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}yw.NAME="Subject Alternative Name";class Aw{static register(e,t){this.items.set(e,t)}static create(e){const t=new Tv(e),r=this.items.get(t.type);return r?new r(e):t}}Aw.items=new Map;class Iw extends Tv{constructor(...e){var t;if(hc.isBufferSource(e[0])){super(e[0]);const t=Ou.parse(this.value,Mp);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new Mp(r.map(e=>new Dp({policyIdentifier:e})));super(_p,s,Ou.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new _v("",{},Rv.toString(e))),e}}Iw.NAME="Certificate Policies",Aw.register(_p,Iw);class vw extends Tv{constructor(...e){var t;if(hc.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new $p({distributionPoint:new Fp({fullName:[new ap({uniformResourceIdentifier:e})]})})),r=new Gp(t);super(Vp,e[1],Ou.serialize(r))}else{const t=new Gp(e[0]);super(Vp,e[1],Ou.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Ou.parse(e.extnValue,Gp);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 rw(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}vw.NAME="CRL Distribution Points";class ww extends Tv{constructor(...e){var t,r,s,i;if(hc.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof yp){const t=new yp(e[0]);super(bp,e[1],Ou.serialize(t))}else{const t=e[0],r=new yp;Ew(r,t,dp,"ocsp"),Ew(r,t,up,"caIssuers"),Ew(r,t,hp,"timeStamping"),Ew(r,t,fp,"caRepository"),super(bp,e[1],Ou.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=[],Ou.parse(e.extnValue,yp).forEach(e=>{switch(e.accessMethod){case dp:this.ocsp.push(new rw(e.accessLocation));break;case up:this.caIssuers.push(new rw(e.accessLocation));break;case hp:this.timeStamping.push(new rw(e.accessLocation));break;case fp:this.caRepository.push(new rw(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Sw(e,"OCSP",this.ocsp),this.caIssuers.length&&Sw(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Sw(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Sw(e,"CA Repository",this.caRepository),e}}function Sw(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new _v("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[_v.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function Ew(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new rw("url",t)),e.push(new mp({accessMethod:r,accessLocation:Ou.parse(t.rawData,ap)}))})}ww.NAME="Authority Info Access";class Cw extends Uv{constructor(...e){let t;if(hc.isBufferSource(e[0]))t=hc.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>hc.toArrayBuffer(e)):[];t=Ou.serialize(new Eb({type:r,values:s}))}super(t,Eb)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new _v("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[_v.NAME]===Cw.NAME&&(e[_v.NAME]=Rv.toString(this.type)),e}}Cw.NAME="Attribute";class kw extends Cw{constructor(...e){var t;if(hc.isBufferSource(e[0]))super(e[0]);else{const t=new PI({printableString:e[0]});super(yI,[Ou.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Ou.parse(this.values[0],PI);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[_v.VALUE]=this.password,e}}kw.NAME="Challenge Password";class xw extends Cw{constructor(...e){var t;if(hc.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Kb;for(const e of t)r.push(Ou.parse(e.rawData,Vb));super(AI,[Ou.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Ou.parse(this.values[0],Kb);this.items=e.map(e=>Aw.create(Ou.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[_v.NAME]]=r;return e}}xw.NAME="Extensions";class Bw{static register(e,t){this.items.set(e,t)}static create(e){const t=new Cw(e),r=this.items.get(t.type);return r?new r(e):t}}Bw.items=new Map;const _w="crypto.signatureFormatter";var Rw;let Ow=Rw=class{static createPssParams(e,t){const r=Rw.getHashAlgorithm(e);return r?new gA({hashAlgorithm:r,maskGenAlgorithm:new Db({algorithm:cA,parameters:Ou.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=$A.resolve(zI);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 Db({algorithm:$y,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 Db({algorithm:Jy,parameters:null});case"sha-256":return new Db({algorithm:Xy,parameters:null});case"sha-384":return new Db({algorithm:Zy,parameters:null});case"sha-512":return new Db({algorithm:eA,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=Rw.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Db({algorithm:qy,parameters:Ou.serialize(t)})}return new Db({algorithm:qy,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case $y:return{name:"RSASSA-PKCS1-v1_5"};case Jy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Xy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Zy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case eA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case qy:if(e.parameters){const t=Ou.parse(e.parameters,gA);return{name:"RSA-PSS",hash:$A.resolve(zI).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Ow=Rw=Uu([GA()],Ow),$A.registerSingleton(qI,Ow);let Uw=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Db({algorithm:sA});case"sha-256":return new Db({algorithm:nA});case"sha-384":return new Db({algorithm:aA});case"sha-512":return new Db({algorithm:oA})}return null}toWebAlgorithm(e){switch(e.algorithm){case sA:return{name:"SHA-1"};case nA:return{name:"SHA-256"};case aA:return{name:"SHA-384"};case oA:return{name:"SHA-512"}}return null}};Uw=Uu([GA()],Uw),$A.registerSingleton(qI,Uw);class Tw{addPadding(e,t){const r=hc.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=hc.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=Tw.namedCurveSize.get(r)||Tw.defaultNamedCurveSize,i=new Qy,n=hc.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Ou.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Ou.parse(t,Qy),s=e.namedCurve,i=Tw.namedCurveSize.get(s)||Tw.defaultNamedCurveSize;return Ic(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}Tw.namedCurveSize=new Map,Tw.defaultNamedCurveSize=32;const Nw="1.3.101.110",Dw="1.3.101.111",Mw="1.3.101.112",Pw="1.3.101.113";let Lw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=Mw;break;case"x25519":t=Nw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=Mw;break;case"ed448":t=Pw}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Nw;break;case"x448":t=Dw}}return t?new Db({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case Mw:return{name:"Ed25519"};case Pw:return{name:"EdDSA",namedCurve:"Ed448"};case Nw:return{name:"X25519"};case Dw:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Lw=Uu([GA()],Lw),$A.registerSingleton(qI,Lw);(class extends lw{constructor(e){lw.isAsnEncoded(e)?super(e,jI):super(e),this.tag=cw.CertificateRequestTag}onInit(e){this.tbs=Ou.serialize(e.certificationRequestInfo),this.publicKey=new dw(e.certificationRequestInfo.subjectPKInfo);const t=$A.resolve(zI);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>Bw.create(Ou.serialize(e)));const r=this.getAttribute(AI);this.extensions=[],r instanceof xw&&(this.extensions=r.items),this.subjectName=new Kv(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=Mv.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=$A.resolveAll(_w).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=Ou.parse(this.rawData,jI),r=t.certificationRequestInfo,s=new _v("",{Version:`${Qb[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new _v("");for(const t of this.attributes){const r=t.toTextObject();e[r[_v.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new _v("",{Algorithm:Ov.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class Hw extends lw{constructor(e){lw.isAsnEncoded(e)?super(e,$b):super(e),this.tag=cw.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Ou.serialize(t),this.serialNumber=Ac.ToHex(t.serialNumber),this.subjectName=new Kv(t.subject),this.subject=new Kv(t.subject).toString(),this.issuerName=new Kv(t.issuer),this.issuer=this.issuerName.toString();const r=$A.resolve(zI);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=>Aw.create(Ou.serialize(e)))),this.publicKey=new dw(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=Mv.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 dw)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(hc.isBufferSource(i)){const e=new dw(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=$A.resolveAll(_w).reverse();let a=null;for(const e of n)if(a=e.toWebSignature(r,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const o=await t.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return o;{const t=(e.date||new Date).getTime();return o&&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=Mv.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=Mv.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Ou.parse(this.rawData,$b),r=t.tbsCertificate,s=new _v("",{Version:`${Qb[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Ov.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new _v("",{"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 _v("");for(const t of this.extensions){const r=t.toTextObject();e[r[_v.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new _v("",{Algorithm:Ov.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}Hw.NAME="Certificate";class Vw{static async createSelfSigned(e,t=Mv.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=Mv.get()){var r;let s;s=e.publicKey instanceof dw?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:hc.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const i=e.serialNumber?hc.toUint8Array(Ac.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));i[0]>127&&(i[0]&=127),i.length>1&&0===i[0]&&(i[1]|=128);const n=e.notBefore||new Date,a=e.notAfter||new Date(n.getTime()+31536e6),o=new $b({tbsCertificate:new Fb({version:Qb.v3,serialNumber:i,validity:new Lb({notBefore:n,notAfter:a}),extensions:new Kb((null===(r=e.extensions)||void 0===r?void 0:r.map(e=>Ou.parse(e.rawData,Vb)))||[]),subjectPublicKeyInfo:Ou.parse(s,Mb)})});if(e.subject){const t=e.subject instanceof Kv?e.subject:new Kv(e.subject);o.tbsCertificate.subject=Ou.parse(t.toArrayBuffer(),rp)}if(e.issuer){const t=e.issuer instanceof Kv?e.issuer:new Kv(e.issuer);o.tbsCertificate.issuer=Ou.parse(t.toArrayBuffer(),rp)}const c={hash:"SHA-256"},l="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},d=$A.resolve(zI);o.tbsCertificate.signature=o.signatureAlgorithm=d.toAsnAlgorithm(l);const u=Ou.serialize(o.tbsCertificate),h="signingKey"in e?await t.subtle.sign(l,e.signingKey,u):e.signature,f=$A.resolveAll(_w).reverse();let g=null;for(const e of f)if(g=e.toAsnSignature(l,h),g)break;if(!g)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return o.signatureValue=g,new Hw(Ou.serialize(o))}}var Kw;!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"}(Kw||(Kw={})),Aw.register(wp,hw),Aw.register(Xp,pw),Aw.register(db,bw),Aw.register(xb,mw),Aw.register(Ap,uw),Aw.register(wb,yw),Aw.register(Vp,vw),Aw.register(bp,ww),Bw.register(yI,kw),Bw.register(AI,xw),$A.registerSingleton(_w,class{toAsnSignature(e,t){return hc.toArrayBuffer(t)}toWebSignature(e,t){return hc.toArrayBuffer(t)}}),$A.registerSingleton(_w,Tw),Tw.namedCurveSize.set("P-256",32),Tw.namedCurveSize.set("K-256",32),Tw.namedCurveSize.set("P-384",48),Tw.namedCurveSize.set("P-521",66);const Qw=Zs.new(void 0,"net"),Fw=new class extends If{constructor(){super(...arguments),this.subtle=new jg}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=Cf.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return xf().randomFillSync(t),e}};Mv.set(Fw);const $w="Ed25519",Gw="OKP";var jw,qw,zw;function Ww(e){return`e${function(e){function t(t){const r=t>>3,s=t%8;return(e.at(r)??0)>>s&1}const r=[];for(let s=0;s<8*e.length;s+=5){let e=0;for(let r=s+4;r>=s;r--)e<<=1,e|=t(r);r.push("abcdefghijklmnopqrstuvwxyz234567"[e])}return r.join("")}(e.raw)}`}function Jw(e){const t=new Uint8Array(Buffer.from(e.x??"","base64url"));return Ww(P.blobFrom(t))}async function Yw(e,t){if(e.kty!==Gw)throw new Error(`Unsupported key type ${e.kty}`);const r={name:"EdDSA",namedCurve:$w};return await Fw.subtle.importKey("jwk",e,r,!0,[t===qw.Public?"verify":"sign"])}function Xw(e){return`${e.toString("pem")}\n`}function Zw(e){return{key:eS(e._privKey.raw),ops:{async sign(e,t){const r=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return eS((await vr(r,P.blobFrom(new Uint8Array(t)))).raw)},async verify(e,t,r){const s=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return(await wr([{signature:L.fromBlob(new Uint8Array(r),yr).asOpaque(),key:s.pubKey,message:P.blobFrom(new Uint8Array(t))}]))[0]}}}}function eS(e){if(e.buffer instanceof ArrayBuffer)return e.buffer;const t=new ArrayBuffer(e.length);return new Uint8Array(t).set(e,0),t}function tS(){const e={info:null,verifyCallback:async(t,r)=>{const s=await async function(e){if(Qw.log("Incoming peer. Verifying certificate"),1!==e.length)return Qw.log("Rejecting peer with no certificates."),D.error(jw.NoCertificate);const t=new(uc().X509Certificate)(e[0]);if(t.publicKey.asymmetricKeyType!==$w.toLowerCase())return Qw.log(`Rejecting peer using non-ed25519 certificate: ${t.publicKey.asymmetricKeyType}`),D.error(jw.NotEd25519);const r=t.publicKey.export({format:"jwk"});if(r.kty!==Gw||r.crv!==$w)return Qw.log(`Public key type mismatch: ${r.kty}, ${r.crv}`),D.error(jw.PublicKeyTypeMismatch);const s=Jw(r),i=(t.subjectAltName??"").match(/DNS:([^,]+)/);if(null===i||i[1]!==s)return Qw.log(`AltName mismatch. Expected: '${s}', got: '${i?.[1]}'`),D.error(jw.AltNameMismatch);const n=Buffer.from(r.x??"","base64url");if(!t.verify(t.publicKey))return D.error(jw.IncorrectSignature);const a=L.fromBlob(new Uint8Array(n),mr);return D.ok({id:s,key:a.asOpaque()})}(t);if(s.isError)return function(e){if(void 0===e)return e;switch(e){case jw.AltNameMismatch:return Xo.IllegalParameter;case jw.NotEd25519:return Xo.InsufficientSecurity;case jw.PublicKeyTypeMismatch:return Xo.BadCertificate;case jw.NoCertificate:return Xo.CertificateRequired;case jw.IncorrectSignature:return Xo.BadCertificate;default:throw new Error(`Unexpected VerifyCertError: ${e}`)}}(s.error);e.info=s.ok}};return e}!function(e){e[e.NoCertificate=0]="NoCertificate",e[e.NotEd25519=1]="NotEd25519",e[e.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",e[e.AltNameMismatch=3]="AltNameMismatch",e[e.IncorrectSignature=4]="IncorrectSignature"}(jw||(jw={})),function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(qw||(qw={})),function(e){e[e.LocalClose=0]="LocalClose",e[e.RemoteClose=1]="RemoteClose",e[e.Exception=2]="Exception"}(zw||(zw={}));const rS=Zs.new(void 0,"peers");function sS(e){return`${e.id}@${e.address.host}:${e.address.port}`}class iS{_onPeerConnected=[];_onPeerDisconnected=[];peers=new Map;peerConnected(e){rS.info(`💡 Peer ${sS(e)} connected.`),void 0!==this.peers.get(e.id)&&rS.warn("Replacing older connection."),this.peers.set(e.id,e);for(const t of this._onPeerConnected)t(e)}peerDisconnected(e){rS.info(`⚡︎Peer ${sS(e)} disconnected.`),this.peers.delete(e.id);for(const t of this._onPeerDisconnected)t(e)}isConnected(e){return this.peers.has(e)}noOfConnectedPeers(){return this.peers.size}onPeerConnected(e){return this._onPeerConnected.push(e),()=>{const t=this._onPeerConnected.indexOf(e);-1!==t&&this._onPeerConnected.splice(t,1)}}onPeerDisconnected(e){return this._onPeerDisconnected.push(e),()=>{const t=this._onPeerDisconnected.indexOf(e);-1!==t&&this._onPeerDisconnected.splice(t,1)}}}const nS=Zs.new(void 0,"net");class aS{socket;server;_dial;_peers;listen;started=!1;constructor(e,t,r,s,i){this.socket=e,this.server=t,this._dial=r,this._peers=s,this.listen=i}get isRunning(){return this.started}async start(){if(this.started)throw new Error("Network already started!");this.started=!0,await this.socket.start({host:this.listen.host,port:this.listen.port}),nS.info(`🛜 QUIC socket on ${this.socket.host}:${this.socket.port}`),await this.server.start(),nS.log("🛜 QUIC server listening")}async stop(){if(!this.started)throw new Error("Network not started yet!");nS.info("Stopping the networking."),await this.server.stop(),await this.socket.stop(),this.started=!1,nS.info("Networking stopped.")}get peers(){return this._peers}async dial(e,t={}){return this._dial(e,t)}}const oS=Zs.new(void 0,"net");function cS(e,t,r){e.addEventListener(t.name,async e=>{try{await r(e)}catch(e){oS.error(`Unhandled exception in ${t.name} event handler: ${e}`)}})}class lS{stream;constructor(e){this.stream=e}get streamId(){return this.stream.streamId}get readable(){return this.stream.readable}get writable(){return this.stream.writable}addOnError(e){cS(this.stream,xo,t=>{const r=t.detail instanceof Oa||t.detail instanceof Ua||t.detail instanceof Sa,s=t.detail instanceof Ca,i=r?zw.LocalClose:s?zw.RemoteClose:zw.Exception;e(t.detail,i)})}destroy(){return this.stream.destroy()}}const dS=Zs.new(void 0,"peers");class uS{conn;connectionId;address;id;key;streamEvents=new(jn());constructor(e,t){this.conn=e,dS.log(`👥 [${t.id}] peer connected ${e.remoteHost}:${e.remotePort}`),this.connectionId=e.connectionIdShared.toString(),this.address={host:e.remoteHost,port:e.remotePort},this.id=t.id,this.key=t.key,cS(e,So,e=>{const t=e.detail;dS.log(`🚰 [${this.id}] new stream: [${t.streamId}]`),this.streamEvents.emit("stream",new lS(t))}),cS(e,vo,e=>{dS.error(`❌ [${this.id}] connection failed: ${e.detail}`)})}addOnIncomingStream(e){this.streamEvents.on("stream",e)}openStream(){const e=this.conn.newStream("bidi");return dS.log(`🚰 [${this.id}] opening stream: [${e.streamId}]`),new lS(e)}async disconnect(){dS.log(`👋 [${this.id}] disconnecting`),await this.conn.stop({isApp:!0})}}const hS=Zs.new(void 0,"net");class fS{static async setup({host:e,port:t,protocols:r,key:s}){const i=Zs.getLevel("net")>$s.TRACE?ei.WARN:ei.DEBUG,n=new yi("quic",i,[new Ii(fi`${ai}:${ci}:${di}`)]),a=function(e){const t={kty:Gw,crv:$w,x:Buffer.from(e.pubKey.raw).toString("base64url"),d:Buffer.from(e._privKey.raw).toString("base64url")};return{publicKey:{...t,d:void 0},privateKey:{...t,x:void 0}}}(s),o=await async function(e){const t=await Yw(e.privateKey,qw.Private),r=await Fw.subtle.exportKey("pkcs8",t);return["-----BEGIN PRIVATE KEY-----",...Buffer.from(r).toString("base64").match(/.{1,64}/g)??[],"-----END PRIVATE KEY-----",""].join("\n")}(a),c=await async function({certId:e,subjectKeyPair:t,issuerKeyPair:r,subjectAttrsExtra:s=[],issuerAttrsExtra:i=[],now:n=new Date}){const a=await Yw(t.publicKey,qw.Public),o=await Yw(t.privateKey,qw.Private),c=await Yw(r.privateKey,qw.Private),l=await Yw(r.publicKey,qw.Public),d=new Date(n.getTime()-n.getTime()%1e3),u=new Date(n.getTime()-n.getTime()%1e3+2e3),h=await Fw.subtle.digest("SHA-256",await Fw.subtle.exportKey("spki",a)),f=await Fw.subtle.digest("SHA-256",await Fw.subtle.exportKey("spki",l)),g=e.toString().substring(2),p=Buffer.from(h).toString("hex"),b=Buffer.from(f).toString("hex"),m={serialNumber:g,notBefore:d,notAfter:u,subject:[{CN:[p]},...s.filter(e=>!("CN"in e))],issuer:[{CN:[b]},...i.filter(e=>!("CN"in e))],signingAlgorithm:c.algorithm,publicKey:a,signingKey:o,extensions:[new hw(!0),new bw(gw.keyCertSign|gw.cRLSign|gw.digitalSignature|gw.nonRepudiation|gw.keyAgreement|gw.keyEncipherment|gw.dataEncipherment),new pw([]),new yw([{type:"dns",value:Jw(t.publicKey)}]),await mw.create(a)]};return m.signingKey=c,await Vw.create(m)}({certId:P.blobFromString("QUIC Networking"),subjectKeyPair:a,issuerKeyPair:a}),l=tS(),d={keepAliveIntervalTime:3e3,maxIdleTimeout:6e3,applicationProtos:r,cert:Xw(c),key:o,verifyPeer:!0,verifyCallback:l.verifyCallback};hS.info(`🆔 Peer id: ** ${Ww(s.pubKey)}@${e}:${t} ** (pubkey: ${s.pubKey})`);const u=new To({logger:n.getChild("socket")}),h=new ac({socket:u,config:d,crypto:Zw(s),logger:n.getChild("server")}),f=new iS;function g(e,t){const r=new uS(e,t);return cS(r.conn,wo,()=>f.peerDisconnected(r)),f.peerConnected(r),r}return cS(h,mo,e=>hS.error(`🛜 Server error: ${e}`)),cS(h,yo,e=>hS.error(`🛜 Server stopped: ${e}`)),cS(h,bo,async e=>{const t=e.detail;if(null!==l.info){if(l.info.key.isEqualTo(s.pubKey))return hS.log(`🛜 Rejecting connection from ourself from ${t.remoteHost}:${t.remotePort}`),void await t.stop();if(f.isConnected(l.info.id))return hS.log(`🛜 Rejecting duplicate connection with peer ${l.info.id} from ${t.remoteHost}:${t.remotePort}`),void await t.stop();hS.log(`🛜 Server handshake with ${t.remoteHost}:${t.remotePort}`),g(t,l.info),l.info=null,await t.start()}else await t.stop()}),new aS(u,h,async function(e,t){const r=tS(),s=lc.createQUICClient({socket:u,host:e.host,port:e.port,crypto:{ops:{async randomBytes(e){dc.webcrypto.getRandomValues(new Uint8Array(e))}}},config:{...d,verifyCallback:r.verifyCallback},logger:n.getChild("client")},{signal:t.signal}),i=await s;if(cS(i,go,()=>{hS.log("⚰️ Client connection closed.")}),cS(i,ho,e=>{hS.error(`🔴 Client error: ${e.detail}`)}),null===r.info)throw new Error("Client connected, but there is no peer details!");if(void 0!==t.verifyName&&t.verifyName!==r.info.id)throw new Error(`Client connected, but the id didn't match. Expected: ${t.verifyName}, got: ${r.info.id}`);return hS.log(`🤝 Client handshake with: ${e.host}:${e.port}`),g(i.connection,r.info)},f,{host:e,port:t})}}const gS=t(import.meta.url)("node:buffer");function pS(e){return de(ne(e.length))}function bS(e,t){let r=gS.Buffer.alloc(0),s=-1;return i=>{r=gS.Buffer.concat([r,i]);do{if(-1===s){if(r.length<4)break;s=r.readUint32LE(),r=r.subarray(4)}if(r.length<s)break;if(r.length>16777216){t();break}const i=r.subarray(0,s);r=r.subarray(s),s=-1,e(new Uint8Array(i))}while(r.length>0)}}class mS{id;ip;port;constructor(e,t,r){this.id=e,this.ip=t,this.port=r}get host(){return this.ip}toString(){return`${this.id}@${this.ip}:${this.port}`}}const yS=Zs.new(void 0,"net:conn");class AS{network;peerInfo=new Map;constructor(e){this.network=e,e.peers.onPeerConnected(e=>(this.updatePeer(e),O)),e.peers.onPeerDisconnected(e=>(this.scheduleReconnect(e.id),O))}setAuxData(e,t,r){this.peerInfo.get(e)?.aux.set(t.id,r)}getAuxData(e,t){return this.peerInfo.get(e)?.aux.get(t.id)}withAuxData(e,t,r){const s=r(this.getAuxData(e,t));this.setAuxData(e,t,s)}getPeerCount(){return this.network.peers.noOfConnectedPeers()}*getConnectedPeers(){for(const e of this.peerInfo.values())null!==e.peerRef&&(yield e)}updatePeer(e){const t=this.peerInfo.get(e.id);void 0!==t?(t.peerRef=e,t.lastConnected=Date.now(),t.currentRetry=Math.floor(t.currentRetry/2),t.address=e.address):this.peerInfo.set(e.id,{peerId:e.id,address:e.address,peerRef:e,lastConnected:Date.now(),maxRetries:5,currentRetry:0,backgroundTask:new AbortController,aux:new Map})}async scheduleReconnect(e){const t=this.peerInfo.get(e);if(void 0===t)return;t.peerRef=null,t.backgroundTask=new AbortController;const r=t.backgroundTask.signal;for(;;){if(t.currentRetry+=1,t.currentRetry>=t.maxRetries)return this.peerInfo.delete(e),void yS.log(`[${e}] max retries reached. Removing peer.`);const s=Math.min(3*t.currentRetry*t.currentRetry,3600);try{await(0,Fs.setTimeout)(1e3*s,void 0,{signal:r})}catch{return}if(null!==t.peerRef)return;try{return yS.trace(`[${e}] Attempting to connect to peer at ${t.address.host}:${t.address.port}.`),void await this.network.dial(t.address,{signal:r,verifyName:t.peerId})}catch{if(r.aborted)return;yS.trace(`[${e}] attempt failed. Will retry (${t.currentRetry}/${t.maxRetries})`)}}}addPersistentRetry(e){for(const t of e)this.peerInfo.set(t.id,{peerId:t.id,address:{host:t.host,port:t.port},maxRetries:2**32,currentRetry:0,peerRef:null,lastConnected:0,backgroundTask:new AbortController,aux:new Map}),this.scheduleReconnect(t.id)}}function IS(e){return te(e)}function vS(e,t){return e().catch(t)}const wS=Zs.new(void 0,"stream");class SS{incomingHandlers=new Map;outgoingHandlers=new Map;streams=new Map;backgroundTasks=new Map;registerIncomingHandlers(...e){for(const t of e)this.incomingHandlers.set(t.kind,t)}registerOutgoingHandlers(...e){for(const t of e)this.outgoingHandlers.set(t.kind,t)}getPeer(e){return this.streams.get(e)?.peer??null}async waitForFinish(){for(const e of this.backgroundTasks.values())await e}withStreamOfKind(e,t,r){for(const s of this.streams.values())if(s.handler.kind===t&&s.peer.id===e)return void r(s.handler,s.streamSender)}withNewStream(e,t,r){const s=this.outgoingHandlers.get(t);if(void 0===s)throw new Error(`Unsupported outgoing stream kind: ${t}`);const i=e.openStream(),n=this.registerStream(e,s,i,P.empty());n.bufferAndSend(P.blobFromNumbers([t]),!1),r(s,n)}async onIncomingStream(e,t){const{readable:r,streamId:s}=t,i=r.getReader();let n=P.empty();try{const t=await i.read();n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array),wS.trace(`🚰 --\x3e [${e.id}:${s}] Initial data: ${n}`)}finally{i.releaseLock()}if(n.raw.length<1)throw new Error(`Expected 1-byte stream identifier, got: ${n}`);const a=IS(n.raw[0]),o=this.incomingHandlers.get(a);if(void 0===o)throw new Error(`Unsupported stream kind: ${a}`);wS.log(`🚰 --\x3e [${e.id}:${t.streamId}] Stream identified as: ${a}`),this.registerStream(e,o,t,P.blobFrom(n.raw.subarray(1)))}registerStream(e,t,r,s){const i=(n=r.streamId,ne(n));var n;const a=(r,s)=>{this.streams.delete(i),this.backgroundTasks.delete(i),s===zw.Exception&&wS.error(`🚰 --- [${e.id}:${i}] Stream error: ${r}. Disconnecting peer.`),s!==zw.LocalClose&&(t.onClose(i,!0),e.disconnect())};r.addOnError(a);const o=new ES(i,r,a);this.streams.set(i,{handler:t,streamSender:o,peer:e});const c=vS(()=>async function(e,t,r,s,i){let n=s,a=!1;const o=bS(s=>{const i=P.blobFrom(new Uint8Array(s));wS.trace(`🚰 --\x3e [${e.id}:${r.streamId}] ${i}`),t.onStreamMessage(r,i)},()=>{wS.error(`🚰 --\x3e [${e.id}:${r.streamId}] got too much data. Disconnecting.`),e.disconnect()});for(;;){if(o(n.raw),a)return void wS.log(`🚰 --\x3e [${e.id}:${r.streamId}] remote finished.`);const t=await i.read();a=t.done,n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array)}}(e,t,o,s,r.readable.getReader()),e=>a(e,zw.Exception));return this.streams.has(i)&&this.backgroundTasks.set(i,c),o}}class ES{streamId;internal;onError;bufferedLength=0;bufferedData=[];currentWriterPromise=null;constructor(e,t,r){this.streamId=e,this.internal=t,this.onError=r}bufferAndSend(e,t=!0){return!(this.bufferedLength>16384||(this.bufferedData.push({data:e,addPrefix:t}),this.bufferedLength+=e.length,null!==this.currentWriterPromise||(this.currentWriterPromise=vS(async()=>{const e=this.internal.writable.getWriter();try{for(;;){const t=this.bufferedData.shift();if(void 0===t)return;const{data:r,addPrefix:s}=t;wS.trace(`🚰 <-- [${this.streamId}] write: ${r}`),s&&await e.write(pS(r.raw)),await e.write(r.raw),this.bufferedLength-=r.length}}finally{e.releaseLock(),this.currentWriterPromise=null}},e=>this.onError(e,zw.Exception))),0))}close(){vS(async()=>{wS.trace(`🚰 <-- [${this.streamId}] closing`),null!==this.currentWriterPromise&&await this.currentWriterPromise,await this.internal.writable.close()},e=>this.onError(e,zw.Exception))}flush(){return this.currentWriterPromise??Promise.resolve()}}const CS=IS(128);var kS;!function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(kS||(kS={}));class xS extends B{headerHash;direction;maxBlocks;static Codec=Be.Class(xS,{headerHash:Be.bytes(Pe).asOpaque(),direction:Be.u8.convert(e=>te(e),e=>{switch(e){case kS.AscExcl:return kS.AscExcl;case kS.DescIncl:return kS.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:Be.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new xS(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}const BS=Zs.new(void 0,"protocol/ce-128");class _S{chainSpec;getBlockSequence;kind=CS;constructor(e,t){this.chainSpec=e,this.getBlockSequence=t}onStreamMessage(e,t){const r=fe.decodeObject(xS.Codec,t);BS.log(`[${e.streamId}] Client has requested: ${r}`);const s=this.getBlockSequence(e.streamId,r.headerHash,r.direction,r.maxBlocks);e.bufferAndSend(Ae.encodeObject(Be.sequenceFixLen(ys.Codec.View,s.length),s,this.chainSpec)),e.close()}onClose(){}}class RS{chainSpec;kind=CS;promiseResolvers=new Map;promiseRejectors=new Map;constructor(e){this.chainSpec=e}onStreamMessage(e,t){if(!this.promiseResolvers.has(e.streamId))throw new Error("Received an unexpected message from the server.");const r=fe.decodeSequence(ys.Codec.View,t,this.chainSpec);BS.log(`[${e.streamId}] Server returned ${r.length} blocks in ${t.length} bytes of data.`),this.promiseResolvers.get(e.streamId)?.(r),this.promiseResolvers.delete(e.streamId)}onClose(e){this.promiseRejectors.get(e)?.("Stream closed."),this.promiseResolvers.delete(e),this.promiseRejectors.delete(e)}async requestBlockSequence(e,t,r,s){if(this.promiseResolvers.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");return new Promise((i,n)=>{this.promiseResolvers.set(e.streamId,i),this.promiseRejectors.set(e.streamId,n),e.bufferAndSend(Ae.encodeObject(xS.Codec,xS.create({headerHash:t,direction:r,maxBlocks:s}))),e.close()})}}var OS;!function(e){e[e.NoStartBlock=0]="NoStartBlock",e[e.BlockOnFork=1]="BlockOnFork"}(OS||(OS={}));const US=IS(0);class TS extends B{hash;slot;static Codec=Be.Class(TS,{hash:Be.bytes(Pe).asOpaque(),slot:Be.u32.asOpaque()});static create({hash:e,slot:t}){return new TS(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class NS{final;leafs;static Codec=Be.Class(NS,{final:TS.Codec,leafs:Be.sequenceVarLen(TS.Codec)});static create({final:e,leafs:t}){return new NS(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class DS extends B{header;final;static Codec=Be.Class(DS,{header:hs.Codec,final:TS.Codec});static create({header:e,final:t}){return new DS(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const MS=Zs.new(void 0,"protocol/up-0");class PS{spec;getHandshake;onAnnouncement;onHandshake;kind=US;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t,r,s){this.spec=e,this.getHandshake=t,this.onAnnouncement=r,this.onHandshake=s}onStreamMessage(e,t){const{streamId:r}=e;if(!this.handshakes.has(r)){const s=fe.decodeObject(NS.Codec,t);return this.handshakes.set(r,s),this.pendingHandshakes.delete(r)||(MS.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Ae.encodeObject(NS.Codec,this.getHandshake()))),void this.onHandshake(r,s)}const s=fe.decodeObject(DS.Codec,t,this.spec);MS.log(`[${r}] --\x3e got blocks announcement: ${s.final}`),this.onAnnouncement(r,s)}onClose(e){this.handshakes.delete(e),this.pendingHandshakes.delete(e)}sendHandshake(e){const{streamId:t}=e;if(this.handshakes.has(t)||this.pendingHandshakes.has(t))return;const r=this.getHandshake();MS.trace(`[${t}] <-- sending handshake`),this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(Ae.encodeObject(NS.Codec,r))}sendAnnouncement(e,t){const{streamId:r}=e;this.handshakes.has(r)?(MS.trace(`[${r}] <-- sending block announcement: ${t.final}`),e.bufferAndSend(Ae.encodeObject(DS.Codec,t,this.spec))):MS.warn(`[${r}] <-- no handshake yet, skipping announcement.`)}}const LS=31;var HS;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(HS||(HS={}));class VS{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?HS.EmbedLeaf:HS.Leaf:HS.Branch}asBranchNode(){return w(this.getNodeType()===HS.Branch),new KS(this)}asLeafNode(){return w(this.getNodeType()!==HS.Branch),new QS(this)}toString(){return P.blobFrom(this.raw).toString()}}class KS{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new VS;return r.raw.set(e.raw,0),r.raw.set(t.raw,Pe),r.raw[0]&=127,new KS(r)}getLeft(){return L.fromBlob(this.node.raw.subarray(0,Pe),Pe).asOpaque()}getRight(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}}class QS{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new VS;return t.length<=Pe?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,LS),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,LS),1),s.raw.set(r().raw,32)),new QS(s)}getKey(){return L.fromBlob(this.node.raw.subarray(1,32),LS).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===HS.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return P.blobFrom(this.node.raw.subarray(Pe,Pe+e))}getValueHash(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}const FS=IS(129),$S=Be.bytes(64).convert(e=>L.fromBlob(e.raw,64),e=>new VS(e.raw));class GS extends B{key;value;static Codec=Be.Class(GS,{key:Be.bytes(LS),value:Be.blob});static create({key:e,value:t}){return new GS(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class jS extends B{keyValuePairs;static Codec=Be.Class(jS,{keyValuePairs:Be.sequenceVarLen(GS.Codec)});static create({keyValuePairs:e}){return new jS(e)}constructor(e){super(),this.keyValuePairs=e}}class qS extends B{headerHash;startKey;endKey;maximumSize;static Codec=Be.Class(qS,{headerHash:Be.bytes(Pe).asOpaque(),startKey:Be.bytes(LS),endKey:Be.bytes(LS),maximumSize:Be.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new qS(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const zS=Zs.new(void 0,"protocol/ce-129");class WS{isServer;getBoundaryNodes;getKeyValuePairs;kind=FS;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(zS.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=fe.decodeObject(qS.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return zS.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Ae.encodeObject(Be.sequenceVarLen($S),s)),e.bufferAndSend(Ae.encodeObject(jS.Codec,jS.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,fe.decodeObject(Be.sequenceVarLen($S),t)),void zS.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(fe.decodeObject(jS.Codec,t)),zS.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(Ae.encodeObject(qS.Codec,qS.create({headerHash:t,startKey:r,endKey:r,maximumSize:ne(4096)}))),e.close()}}IS(131),IS(132);class JS extends B{epochIndex;ticket;static Codec=Be.Class(JS,{epochIndex:Be.u32.asOpaque(),ticket:Rt.Codec});static create({epochIndex:e,ticket:t}){return new JS(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}Zs.new(void 0,"protocol/ce-131-ce-132"),IS(133);class YS extends B{coreIndex;workPackage;static Codec=Be.Class(YS,{coreIndex:Be.u16.asOpaque(),workPackage:Wr.Codec});static create({coreIndex:e,workPackage:t}){return new YS(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}Zs.new(void 0,"protocol/ce-133"),Be.blob,IS(134);class XS extends B{coreIndex;segmentsRootMappings;static Codec=Be.Class(XS,{coreIndex:Be.u16.asOpaque(),segmentsRootMappings:Be.sequenceVarLen(rs.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new XS(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class ZS extends B{workReportHash;signature;static Codec=Be.Class(ZS,{workReportHash:Be.bytes(Pe).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,signature:t}){return new ZS(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}Zs.new(void 0,"protocol/ce-134"),IS(135);class eE extends B{report;slot;signatures;static Codec=Be.Class(eE,{report:ss.Codec,slot:Be.u32.asOpaque(),signatures:kt(e=>xt(ns.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new eE(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}Zs.new(void 0,"protocol/ce-135");const tE={id:Symbol("sync")},rE=Zs.new(void 0,"net:sync");class sE{spec;streamManager;connections;blocks;onNewBlocks;static start(e,t,r,s,i){const n=new sE(e,t,r,s,i),a=e=>t.getPeer(e),o=new PS(e,()=>n.getUp0Handshake(),(e,t)=>{const r=a(e);null!==r&&n.onUp0Annoucement(r,t)},(e,t)=>{const r=a(e);null!==r&&n.onUp0Handshake(r,t)});return t.registerIncomingHandlers(o),t.registerIncomingHandlers(new _S(e,(e,t,r,s)=>{const i=a(e);return null!==i?n.handleGetBlockSequence(i,t,r,s):[]})),t.registerOutgoingHandlers(o),t.registerOutgoingHandlers(new RS(e)),n}othersBest;constructor(e,t,r,s,i){this.spec=e,this.streamManager=t,this.connections=r,this.blocks=s,this.onNewBlocks=i;const n=s.getBestHeaderHash(),a=s.getHeader(n);if(null===a)throw new Error(`Best header ${n} missing in the database?`);this.othersBest=TS.create({hash:n,slot:a.timeSlotIndex.materialize()})}onUp0Handshake(e,t){const{hash:r,slot:s}=t.final;this.connections.withAuxData(e.id,tE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:null}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=null,e)),this.othersBest.slot<s&&(this.othersBest=t.final)}onUp0Annoucement(e,t){const{hash:r,slot:s}=t.final,i=function(e,t){const r=Ae.encodeObject(hs.Codec,e,t);return new He(qe(r).asOpaque(),e)}(t.header,this.spec);rE.info(`[${e.id}] --\x3e Received new header #${t.header.timeSlotIndex}: ${i.hash}`),this.connections.withAuxData(e.id,tE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:i}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=i,e)),this.othersBest.slot<i.data.timeSlotIndex&&(this.othersBest=TS.create({hash:i.hash,slot:i.data.timeSlotIndex}))}getUp0Handshake(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=t?.timeSlotIndex.materialize(),s=TS.create({hash:e,slot:r??Ur(0)});return NS.create({final:s,leafs:[]})}openUp0(e){this.streamManager.withNewStream(e,US,(e,t)=>(e.sendHandshake(t),O))}broadcastHeader(e){const t=e.data.timeSlotIndex.materialize(),r=DS.create({header:e.data.materialize(),final:TS.create({hash:e.hash,slot:t})}),s=this.connections.getConnectedPeers();for(const i of s)this.streamManager.withStreamOfKind(i.peerId,US,(s,n)=>(rE.log(`[${i.peerId}] <-- Broadcasting new header #${t}: ${e.hash}`),s.sendAnnouncement(n,r),O))}handleGetBlockSequence(e,t,r,s){const i=ne(Math.min(s,128)),n=function(e,t,r,s,i){const n=r=>{const s=t.getHeader(r),i=t.getExtrinsic(r);if(null===s||null===i)return null;const n=P.blobFromParts(s.encoded().raw,i.encoded().raw);return fe.decodeObject(ys.Codec.View,n,e)},a=n(r);if(null===a)return D.error(OS.NoStartBlock);if(s===kS.AscExcl){const e=[],s=a.header.view().timeSlotIndex.materialize();let o=t.getBestHeaderHash();for(;;){const a=t.getHeader(o);if(null===a||a.timeSlotIndex.materialize()<s)return D.error(OS.BlockOnFork);if(r.isEqualTo(o))return D.ok(e.reverse().slice(0,i).flatMap(e=>{const t=n(e);return null===t?[]:[t]}));e.push(o),o=a.parentHeaderHash.materialize()}}const o=[a];let c=a;for(let e=0;e<i;e++){const e=n(c.header.view().parentHeaderHash.materialize());if(null===e)break;o.push(e),c=e}return D.ok(o)}(this.spec,this.blocks,t,r,i);return n.isOk?n.ok:n.error===OS.BlockOnFork?(rE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} is on a fork.`),[]):n.error===OS.NoStartBlock?(rE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} missing header or extrinsic.`),[]):void E(n.error)}maintainSync(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=this.connections.getPeerCount();if(null===t)return{kind:iE.OurBestHeaderMissing};const s=t.timeSlotIndex.materialize(),i=this.othersBest,n=i.slot-s;if(rE.trace(`Our best. ${s}. Best seen: ${i.slot}`),n<1)return this.connections.getPeerCount(),rE.trace(`No new blocks. ${r} peers.`),{kind:iE.NoNewBlocks,ours:s,theirs:i.slot};const a=[];rE.log(`Sync ${n} blocks from ${r} peers.`);for(const e of this.connections.getConnectedPeers()){const t=this.connections.getAuxData(e.peerId,tE);if(void 0===t||null===e.peerRef)continue;const r=null!==t.bestHeader?t.bestHeader.data.timeSlotIndex:t.finalBlockSlot,i=null!==t.bestHeader?t.bestHeader.hash:t.finalBlockHash;r<=s||(a.push({peerId:e.peerId,theirs:r,count:r-s}),this.streamManager.withNewStream(e.peerRef,CS,(t,n)=>(vS(async()=>{rE.log(`Fetching blocks from ${e.peerId}.`);const a=await t.requestBlockSequence(n,i,kS.DescIncl,ne(r-s));a.reverse(),this.onNewBlocks(a,e.peerId)},t=>{rE.warn(`[${e.peerId}] --\x3e requesting blocks to import: ${t}`)}),O)))}return{kind:iE.BlocksRequested,ours:s,requested:a}}}var iE;!function(e){e[e.OurBestHeaderMissing=1]="OurBestHeaderMissing",e[e.NoNewBlocks=2]="NoNewBlocks",e[e.BlocksRequested=3]="BlocksRequested"}(iE||(iE={}));const nE=Zs.new(void 0,"jamnps");function aE(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(!ie(n))throw new Error(`Invalid port number: "${i}"`);return new mS(t,s,n)}class oE extends B{bootnodes;id;genesisHeader;genesisState;static fromJson=ee.object({bootnodes:ee.optional(ee.array(ee.fromString(aE))),id:"string",genesis_header:Tt.bytesBlobNoPrefix,genesis_state:ee.map(Tt.bytesNNoPrefix(31),Tt.bytesBlobNoPrefix)},e=>oE.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=P.empty(),genesisState:s=new Map}){return new oE({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 cE=t(import.meta.url)("node:fs");var lE=a.n(cE);const dE=t(import.meta.url)("node:os");var uE=a.n(dE);const hE=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-default","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"}'),fE=JSON.parse('{"$schema":"https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":true},"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 gE{omitSealVerification;static fromJson=ee.object({omit_seal_verification:"boolean"},gE.new);static new({omit_seal_verification:e}){return new gE(e)}constructor(e){this.omitSealVerification=e}}const pE="dev",bE="default",mE={name:uE().hostname(),config:bE};var yE;!function(e){e.Tiny="tiny",e.Full="full"}(yE||(yE={}));const AE=ee.fromString((e,t)=>{switch(e){case yE.Tiny:return yE.Tiny;case yE.Full:return yE.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class IE{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=ee.object({$schema:"string",version:"number",flavor:AE,chain_spec:oE.fromJson,database_base_path:"string",authorship:gE.fromJson},IE.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 IE(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}}const vE=t(import.meta.url)("node:worker_threads"),wE="best hash and posterior state root";class SE{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:L.fromBlob(t,Pe).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(wE,e.raw)}getBestHeaderHash(){const e=this.root.db.get(wE);return void 0===e?L.zero(Pe).asOpaque():L.fromBlob(e,Pe).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:fe.decodeObject(hs.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:fe.decodeObject(ms.Codec.View,t,this.chainSpec)}}const EE=(CE={open:()=>r.open},kE={},a.d(kE,CE),kE);var CE,kE;class xE{db;constructor(e,t=!1){this.db=EE.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class BE{serviceId;output;static Codec=Be.Class(BE,{serviceId:Be.u32.asOpaque(),output:Be.bytes(Pe)});static create(e){return new BE(e.serviceId,e.output)}constructor(e,t){this.serviceId=e,this.output=t}}const _E=e=>Ce.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=qe(e.skipEncoded(r));return new He(s.asOpaque(),e.decode(t))},e.skip,e.View);class RE extends B{workReport;timeout;static Codec=Be.Class(RE,{workReport:_E(ss.Codec),timeout:Be.u32.asOpaque()});static create({workReport:e,timeout:t}){return new RE(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}function OE(e,t){return w(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const UE=e=>kt(t=>xt(e,{fixedLength:t.coresCount})),TE=()=>ke(Be.sequenceVarLen(Be.bytes(Pe))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return It.fromSortedArray(ME,t)}),NE=TE();class DE{goodSet;badSet;wonkySet;punishSet;static Codec=Be.Class(DE,{goodSet:NE,badSet:NE,wonkySet:NE,punishSet:TE()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new DE(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 DE(It.fromSortedArray(ME,e),It.fromSortedArray(ME,t),It.fromSortedArray(ME,r),It.fromSortedArray(ME,s))}}function ME(e,t){return e.compare(t)}class PE{service;gasLimit;static Codec=Be.Class(PE,{service:Be.u32.asOpaque(),gasLimit:Be.u64.asOpaque()});static create({service:e,gasLimit:t}){return new PE(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class LE{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=Be.Class(LE,{manager:Be.u32.asOpaque(),authManager:v.isGreaterOrEqual(h.V0_6_7)?UE(Be.u32.asOpaque()):kt(e=>Be.u32.asOpaque().convert(e=>e[0],t=>OE(new Array(e.coresCount).fill(t),e))),validatorsManager:Be.u32.asOpaque(),autoAccumulateServices:ke(Be.sequenceVarLen(PE.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new LE(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const HE=P.blobFromString("peak");class VE{hasher;mountains;static empty(e){return new VE(e)}static fromPeaks(e,t){return new VE(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(KE.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=KE.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 L.zero(Pe).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(HE,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 KE{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new KE(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new KE(i,n)}mergeWith(e,t){return KE.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}class QE extends B{headerHash;mmr;postStateRoot;reported;static Codec=Be.Class(QE,{headerHash:Be.bytes(Pe).asOpaque(),mmr:Be.object({peaks:ke(Be.sequenceVarLen(Be.optional(Be.bytes(Pe))))}),postStateRoot:Be.bytes(Pe).asOpaque(),reported:_t(rs.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new QE(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}class FE extends B{blocks;static Codec=Be.Class(FE,{blocks:xt(QE.Codec,{minLength:0,maxLength:8,typicalLength:8})});static create(e){return new FE(e.blocks)}constructor(e){super(),this.blocks=e}}class $E extends B{headerHash;accumulationResult;postStateRoot;reported;static Codec=Be.Class($E,{headerHash:Be.bytes(Pe).asOpaque(),accumulationResult:Be.bytes(Pe),postStateRoot:Be.bytes(Pe).asOpaque(),reported:_t(rs.Codec,e=>e.workPackageHash)});static create({headerHash:e,accumulationResult:t,postStateRoot:r,reported:s}){return new $E(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.accumulationResult=t,this.postStateRoot=r,this.reported=s}}class GE extends B{blocks;accumulationLog;static Codec=Be.Class(GE,{blocks:xt($E.Codec,{minLength:0,maxLength:8,typicalLength:8}),accumulationLog:Be.object({peaks:ke(Be.sequenceVarLen(Be.optional(Be.bytes(Pe))))})});static create(e){return new GE(e.blocks,e.accumulationLog)}constructor(e,t){super(),this.blocks=e,this.accumulationLog=t}}class jE extends B{current;legacy;static Codec=Ce.new("RecentBlocksHistory",v.isGreaterOrEqual(h.V0_6_7)?GE.Codec.sizeHint:FE.Codec.sizeHint,(e,t)=>v.isGreaterOrEqual(h.V0_6_7)?GE.Codec.encode(e,t.asCurrent()):FE.Codec.encode(e,t.asLegacy()),e=>{if(v.isGreaterOrEqual(h.V0_6_7)){const t=GE.Codec.decode(e);return jE.create(t)}const t=FE.Codec.decode(e);return jE.legacyCreate(t)},e=>v.isGreaterOrEqual(h.V0_6_7)?GE.Codec.sizeHint:FE.Codec.sizeHint);static create(e){return new jE(e,null)}static legacyCreate(e){return new jE(null,e)}static empty(){return v.isGreaterOrEqual(h.V0_6_7)?jE.create(GE.create({blocks:[],accumulationLog:{peaks:[]}})):jE.legacyCreate(FE.create({blocks:[]}))}static accumulationResult(e,{hasher:t}){return v.isGreaterOrEqual(h.V0_6_7)?e.accumulationResult:VE.fromPeaks(t,e.mmr).getSuperPeakHash()}constructor(e,t){super(),this.current=e,this.legacy=t}get blocks(){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return this.current.blocks;if(null!==this.legacy)return this.legacy.blocks;throw new Error("RecentBlocksHistory is in invalid state")}asCurrent(){if(null===this.current)throw new Error("Cannot access current RecentBlocks format");return this.current}asLegacy(){if(null===this.legacy)throw new Error("Cannot access legacy RecentBlocks format");return this.legacy}updateBlocks(e){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return jE.create(GE.create({...this.current,blocks:e}));if(null!==this.legacy)return jE.legacyCreate(FE.create({blocks:e}));throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!")}}const qE=128;class zE extends B{bandersnatch;ed25519;bls;metadata;static Codec=Be.Class(zE,{bandersnatch:Be.bytes(Te).asOpaque(),ed25519:Be.bytes(mr).asOpaque(),bls:Be.bytes(Me).asOpaque(),metadata:Be.bytes(qE)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new zE(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var WE;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(WE||(WE={}));const JE=Be.bytes(Te).asOpaque();class YE extends B{kind;keys;tickets;static Codec=kt(e=>Be.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Pe*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===WE.Keys?e.sequenceFixLen(JE,t.keys):e.sequenceFixLen(Ot.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===WE.Keys){const s=t.sequenceFixLen(JE,r);return YE.keys(Vr(s,e))}if(s===WE.Tickets){const s=t.sequenceFixLen(Ot.Codec,r);return YE.tickets(Vr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==WE.Keys){if(r!==WE.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(Ot.Codec,e.epochLength)}else t.sequenceFixLen(JE,e.epochLength)}));static keys(e){return new YE(WE.Keys,e,void 0)}static tickets(e){return new YE(WE.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class XE{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=Be.Class(XE,{nextValidatorData:Hr(zE.Codec),epochRoot:Be.bytes(De).asOpaque(),sealingKeySeries:YE.Codec,ticketsAccumulator:ke(Be.sequenceVarLen(Ot.Codec)).convert(R,mt)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new XE(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}const ZE={bytes:0,isExact:!0},eC=e=>Ce.new("ignoreValue",ZE,(e,t)=>{},t=>e,e=>{});class tC extends B{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;gratisStorage;storageUtilisationCount;created;lastAccumulation;parentService;static Codec=v.isGreaterOrEqual(h.V0_6_7)?Be.Class(tC,{codeHash:Be.bytes(Pe).asOpaque(),balance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,gratisStorage:Be.u64,storageUtilisationCount:Be.u32,created:Be.u32.convert(e=>e,Ur),lastAccumulation:Be.u32.convert(e=>e,Ur),parentService:Be.u32.convert(e=>e,Nr)}):Be.Class(tC,{codeHash:Be.bytes(Pe).asOpaque(),balance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,storageUtilisationCount:Be.u32,gratisStorage:eC(oe(0)),created:eC(Ur(0)),lastAccumulation:eC(Ur(0)),parentService:eC(Nr(0))});static create(e){return new tC(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.gratisStorage,e.storageUtilisationCount,e.created,e.lastAccumulation,e.parentService)}static calculateThresholdBalance(e,t,r){w(r===oe(0)||v.isGreaterOrEqual(h.V0_6_7),"Gratis storage cannot be non-zero before 0.6.7");const s=100n+10n*BigInt(e)+1n*t-r;return oe(s<0n?0:s>=2n**64n?2n**64n-1n:s)}constructor(e,t,r,s,i,n,a,o,c,l){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.gratisStorage=n,this.storageUtilisationCount=a,this.created=o,this.lastAccumulation=c,this.parentService=l}}class rC extends B{hash;blob;static Codec=Be.Class(rC,{hash:Be.bytes(Pe).asOpaque(),blob:Be.blob});static create({hash:e,blob:t}){return new rC(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class sC extends B{key;value;static Codec=Be.Class(sC,{key:Be.blob.convert(e=>e,e=>e),value:Be.blob});static create({key:e,value:t}){return new sC(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function iC(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class nC{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 aC,oC,cC;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(aC||(aC={}));class lC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new lC(e,{kind:aC.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new lC(e,{kind:aC.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new lC(e,{kind:aC.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case aC.Provide:return this.action.preimage.hash;case aC.Remove:return this.action.hash;case aC.UpdateOrAdd:return this.action.item.hash}throw E(this.action)}get length(){switch(this.action.kind){case aC.Provide:return ne(this.action.preimage.blob.length);case aC.Remove:return this.action.length;case aC.UpdateOrAdd:return this.action.item.length}throw E(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(oC||(oC={}));class dC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new dC(e,{kind:oC.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new dC(e,{kind:oC.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(cC||(cC={}));class uC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new uC(e,{kind:cC.Set,storage:t})}static remove({serviceId:e,key:t}){return new uC(e,{kind:cC.Remove,key:t})}get key(){return this.action.kind===cC.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===cC.Remove?null:this.action.storage.value}}const hC=v.isSuite(f.W3F_DAVXY)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.JAMDUNA,h.V0_6_7)?Be.u32.asOpaque():Be.varU32.convert(e=>ne(e),e=>Nr(e));class fC{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=Be.Class(fC,{blocks:Be.u32,tickets:Be.u32,preImages:Be.u32,preImagesSize:Be.u32,guarantees:Be.u32,assurances:Be.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new fC(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=ne(0);return new fC(e,e,e,e,e,e)}}const gC=Be.varU32.convert(e=>ne(e),e=>se(e)),pC=Be.varU64.convert(e=>oe(e),e=>Dr(e));class bC{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=Be.Class(bC,{dataAvailabilityLoad:Be.varU32,popularity:gC,imports:gC,exports:gC,extrinsicSize:Be.varU32,extrinsicCount:gC,bundleSize:Be.varU32,gasUsed:pC});static create(e){return new bC(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,a,o){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=a,this.gasUsed=o}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new bC(e,t,t,t,e,t,e,r)}}class mC{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=Be.Class(mC,{providedCount:gC,providedSize:Be.varU32,refinementCount:Be.varU32,refinementGasUsed:pC,imports:gC,exports:gC,extrinsicSize:Be.varU32,extrinsicCount:gC,accumulateCount:Be.varU32,accumulateGasUsed:pC,onTransfersCount:Be.varU32,onTransfersGasUsed:pC});static create(e){return new mC(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,a,o,c,l,d,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=a,this.extrinsicCount=o,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=d,this.onTransfersGasUsed=u}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new mC(t,e,e,r,t,t,e,t,e,r,e,r)}}class yC{current;previous;cores;services;static Codec=Be.Class(yC,{current:Hr(fC.Codec),previous:Hr(fC.Codec),cores:UE(bC.Codec),services:Be.dictionary(hC,mC.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new yC(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 AC,IC;(IC=AC||(AC={}))[IC.DuplicateService=0]="DuplicateService",IC[IC.NoService=1]="NoService",IC[IC.PreimageExists=2]="PreimageExists";class vC extends B{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.toString())?.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.values()).map(e=>e.key),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=pt.new(),i=new Map,n=pt.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,rC.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 nC(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.toString(),sC.create({key:r,value:t}))}return new vC(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class wC extends B{static create(e){return new wC(e)}static partial(e,t){const r=wC.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=vC.copyFrom(t,i);r.set(s,n)}return wC.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,accumulationOutputLog:e.accumulationOutputLog,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.values()).map(e=>e.key),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 a;return Object.assign(this,n),a=this.updateServices(r),a.isError?a:(a=this.updatePreimages(s),a.isError?a:(a=this.updateStorage(i),a.isError?a:(this.removeServices(t),D.ok(O))))}removeServices(e){for(const t of e??[])w(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 D.error(AC.NoService,`Attempting to update storage of non-existing service: ${t}`);if(e===cC.Set){const{key:e,value:t}=r.storage;s.data.storage.set(e.toString(),sC.create({key:e,value:t}))}else if(e===cC.Remove){const{key:e}=r;w(s.data.storage.has(e.toString()),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(e.toString())}else E(e)}return D.ok(O)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return D.error(AC.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===aC.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return D.error(AC.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=ne(s.blob.length),n=new nC(s.hash,r,iC([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===aC.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===aC.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 E(s)}return D.ok(O)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===oC.Create){const{lookupHistory:e}=r;if(this.services.has(t))return D.error(AC.DuplicateService,`${t} already exists!`);this.services.set(t,new vC(t,{info:s,preimages:pt.new(),storage:new Map,lookupHistory:pt.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===oC.Update){const e=this.services.get(t);if(void 0===e)return D.error(AC.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else E(e)}return D.ok(O)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;accumulationOutputLog;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.accumulationOutputLog=e.accumulationOutputLog,this.services=e.services}static empty(e){return new wC({availabilityAssignment:OE(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Lr(Array.from({length:e.validatorsCount},()=>zE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(qE).asOpaque()})),e),nextValidatorData:Lr(Array.from({length:e.validatorsCount},()=>zE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(qE).asOpaque()})),e),currentValidatorData:Lr(Array.from({length:e.validatorsCount},()=>zE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(qE).asOpaque()})),e),previousValidatorData:Lr(Array.from({length:e.validatorsCount},()=>zE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(qE).asOpaque()})),e),disputesRecords:DE.create({goodSet:It.fromSortedArray(ME,[]),badSet:It.fromSortedArray(ME,[]),wonkySet:It.fromSortedArray(ME,[]),punishSet:It.fromSortedArray(ME,[])}),timeslot:Ur(0),entropy:yt.fill(()=>L.zero(Pe).asOpaque(),4),authPools:OE(Array.from({length:e.coresCount},()=>[]),e),authQueues:OE(Array.from({length:e.coresCount},()=>yt.fill(()=>L.zero(Pe).asOpaque(),80)),e),recentBlocks:jE.empty(),statistics:yC.create({current:Lr(Array.from({length:e.validatorsCount},()=>fC.empty()),e),previous:Lr(Array.from({length:e.validatorsCount},()=>fC.empty()),e),cores:OE(Array.from({length:e.coresCount},()=>bC.empty()),e),services:new Map}),accumulationQueue:Vr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Vr(Array.from({length:e.epochLength},()=>bt.new()),e),ticketsAccumulator:[],sealingKeySeries:YE.keys(Vr(Array.from({length:e.epochLength},()=>L.zero(Te).asOpaque()),e)),epochRoot:L.zero(De).asOpaque(),privilegedServices:LE.create({manager:Nr(0),authManager:OE(new Array(e.coresCount).fill(Nr(0)),e),validatorsManager:Nr(0),autoAccumulateServices:[]}),accumulationOutputLog:[],services:new Map})}}const SC=Be.object({storageKeys:Be.sequenceVarLen(Be.blob.convert(e=>e,e=>e)),preimages:Be.sequenceVarLen(Be.bytes(Pe).asOpaque()),lookupHistory:Be.sequenceVarLen(Be.object({hash:Be.bytes(Pe).asOpaque(),length:Be.u32}))});Be.dictionary(Be.u32.asOpaque(),SC,{sortKeys:(e,t)=>e-t});class EC extends B{report;dependencies;static Codec=Be.Class(EC,{report:ss.Codec,dependencies:xt(Be.bytes(Pe).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new EC(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var CC,kC,xC;function BC(e,t){const r=L.zero(Pe);let s=0;for(const i of de(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,Pe-i),s),r.asOpaque()}!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.Omega=14]="Omega",e[e.Xi=15]="Xi",e[e.Theta=16]="Theta",e[e.Delta=255]="Delta"}(CC||(CC={})),function(e){function t(e,t,r){const s=qe(P.blobFromParts(de(t),r.raw)).raw.subarray(0,28),i=L.zero(Pe);let n=0;for(const t of de(e))i.raw[n]=t,i.raw[n+1]=s[n/2],n+=2;const a=n/2;return i.raw.set(s.subarray(a),n),i.asOpaque()}e.index=function(e){const t=L.zero(Pe);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=L.zero(Pe);t.raw[0]=CC.Delta;let r=1;for(const s of de(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-1)),0),t.raw.set(r.raw.subarray(0,28),4),BC(e,t)}return t(e,ne(2**32-1),r)},e.servicePreimage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-2)),0),t.raw.set(r.raw.subarray(1,29),4),BC(e,t)}return t(e,ne(2**32-2),r)},e.serviceLookupHistory=function(e,r,s){if(v.isLessThan(h.V0_6_7)){const t=qe(r),i=L.zero(Pe);return i.raw.set(de(s),0),i.raw.set(t.raw.subarray(2,30),4),BC(e,i)}return t(e,s,r)},e.serviceNested=t}(kC||(kC={})),function(e){e.authPools={key:kC.index(CC.Alpha),Codec:UE(xt(Be.bytes(Pe).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:kC.index(CC.Phi),Codec:UE(Bt(Be.bytes(Pe).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:kC.index(CC.Beta),Codec:jE.Codec,extract:e=>e.recentBlocks},e.safrole={key:kC.index(CC.Gamma),Codec:XE.Codec,extract:e=>XE.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:kC.index(CC.Psi),Codec:DE.Codec,extract:e=>e.disputesRecords},e.entropy={key:kC.index(CC.Eta),Codec:Bt(Be.bytes(Pe).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:kC.index(CC.Iota),Codec:Hr(zE.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:kC.index(CC.Kappa),Codec:Hr(zE.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:kC.index(CC.Lambda),Codec:Hr(zE.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:kC.index(CC.Rho),Codec:UE(Be.optional(RE.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:kC.index(CC.Tau),Codec:Be.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:kC.index(CC.Chi),Codec:LE.Codec,extract:e=>e.privilegedServices},e.statistics={key:kC.index(CC.Pi),Codec:yC.Codec,extract:e=>e.statistics},e.accumulationQueue={key:kC.index(CC.Omega),Codec:Kr(ke(Be.sequenceVarLen(EC.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:kC.index(CC.Xi),Codec:Kr(Be.sequenceVarLen(Be.bytes(Pe).asOpaque()).convert(e=>Array.from(e),e=>bt.from(e))),extract:e=>e.recentlyAccumulated},e.accumulationOutputLog={key:kC.index(CC.Theta),Codec:Be.sequenceVarLen(BE.Codec),extract:e=>e.accumulationOutputLog},e.serviceData=e=>({key:kC.serviceInfo(e),Codec:tC.Codec}),e.serviceStorage=(e,t)=>({key:kC.serviceStorage(e,t),Codec:_C}),e.servicePreimages=(e,t)=>({key:kC.servicePreimage(e,t),Codec:_C}),e.serviceLookupHistory=(e,t,r)=>({key:kC.serviceLookupHistory(e,t,r),Codec:ke(Be.sequenceVarLen(Be.u32))})}(xC||(xC={}));const _C=Ce.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(L.fromBlob(t.raw,t.raw.length)),e=>P.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var RC;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(RC||(RC={}));const OC=P.empty();function UC(e,t){const r=new Uint8Array(4+t.length);return r.set(de(e)),r.set(t.raw,4),P.blobFrom(qe(r).raw)}class TC{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new TC(e,t,r)}static new(e,t,r=[]){return new TC(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}[M](){return this.backend}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(xC.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new NC(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 fe.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return fe.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(xC.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(xC.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(xC.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(xC.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(xC.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(xC.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(xC.timeslot,"timeslot")}get entropy(){return this.retrieve(xC.entropy,"entropy")}get authPools(){return this.retrieve(xC.authPools,"authPools")}get authQueues(){return this.retrieve(xC.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(xC.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(xC.statistics,"statistics")}get accumulationQueue(){return this.retrieve(xC.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(xC.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(xC.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(xC.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(xC.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(xC.privilegedServices,"privilegedServices")}get accumulationOutputLog(){return v.isGreaterOrEqual(h.V0_6_7)?this.retrieve(xC.accumulationOutputLog,"accumulationOutputLog"):[]}}class NC{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){if(v.isLessThan(h.V0_6_7)){const t=4,r=new Uint8Array(t+e.length);r.set(de(this.serviceId)),r.set(e.raw,t);const s=P.blobFrom(qe(r).raw);return this.retrieveOptional(xC.serviceStorage(this.serviceId,s))??null}return this.retrieveOptional(xC.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(xC.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(xC.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(xC.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:iC(r.map(Ur))}}class DC{hasher;nodes=pt.new();constructor(e){this.hasher=e}get(e){return DC.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()!==HS.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 MC extends DC{remove(e){return DC.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return DC.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}const PC=(e,t)=>t.getKey().compare(e.getKey());class LC{nodes;root;static empty(e){return new LC(new MC(e))}static computeStateRoot(e,t){return LC.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new MC(e);for(const e of t)r=HC(r,s,e);return new LC(s,r)}static constructLeaf(e,t,r,s){return QS.fromValue(t,r,()=>s??e.hashConcat(r.raw).asOpaque())}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=LC.constructLeaf(this.nodes.hasher,e,t,r);return this.root=HC(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?L.zero(Pe).asOpaque():this.nodes.hashNode(this.root)}toString(){return QC(this.root,this.nodes)}}function HC(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new VC;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==HS.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),a=KC(r,s.bitIndex),o=a?e.getRight():e.getLeft();s.branchingHistory.push([e,n,a]);const c=t.get(o);if(null===c){if(o.isEqualTo(L.zero(Pe)))return s;throw new Error(`Missing trie node '${o}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=o,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,a]=r;const o=n.getKey(),c=t.insert(s.node);if(o.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(a),[s.node,c];const l=[];let d=KC(i,e.bitIndex);for(;e.bitIndex<248;){d=KC(i,e.bitIndex);const t=KC(o,e.bitIndex);if(d!==t)break;l.push(t),e.bitIndex+=1}const u=L.zero(Pe).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!d&&(a=t.hashNode(n.node));let h=d?KS.fromSubNodes(a,c):KS.fromSubNodes(c,a),f=t.insert(h.node),g=l.pop();for(;void 0!==g;)h=g?KS.fromSubNodes(u,f):KS.fromSubNodes(f,u),f=t.insert(h.node),g=l.pop();return[h.node,f]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[a,o]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?KS.fromSubNodes(e.getLeft(),o):KS.fromSubNodes(o,e.getRight());o=t.insert(c.node),a=c.node,n=s.branchingHistory.pop()}return a}class VC{branchingHistory=[];bitIndex=0;leafToReplace}function KC(e,t){w(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function QC(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===HS.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),a=QC(t.get(s),t),o=QC(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(a)}\n\t-- ${i}: ${n(o)}\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 FC={hashConcat:(e,t=[])=>je([e,...t])};class $C{entries;static serializeInMemory(e,t){return new $C(function(e,t){const r=vt.fromEntries([]);function s(s){r.set(s.key,Ae.encodeObject(s.Codec,s.extract(t),e))}s(xC.authPools),s(xC.authQueues),s(xC.recentBlocks),s(xC.safrole),s(xC.disputesRecords),s(xC.entropy),s(xC.designatedValidators),s(xC.currentValidators),s(xC.previousValidators),s(xC.availabilityAssignment),s(xC.timeslot),s(xC.privilegedServices),s(xC.statistics),s(xC.accumulationQueue),s(xC.recentlyAccumulated),v.isGreaterOrEqual(h.V0_6_7)&&s(xC.accumulationOutputLog);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=xC.serviceData(e);r.set(t,Ae.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=xC.servicePreimages(e,t.hash);r.set(s,Ae.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=xC.serviceStorage(e,t.key);r.set(s,Ae.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=xC.serviceLookupHistory(e,s.hash,s.length);r.set(t,Ae.encodeObject(i,s.slots.slice()))}}return r}(e,t))}static fromDictionaryUnsafe(e){return new $C(e)}static fromEntriesUnsafe(e){return new $C(vt.fromEntries(e))}trieCache=null;constructor(e){this.entries=e}[M](){return this.entries}[Symbol.iterator](){return this.entries[Symbol.iterator]()}getTrie(){if(null===this.trieCache){const e=LC.empty(FC);for(const[t,r]of this.entries)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}get(e){return this.entries.get(e)??null}applyUpdate(e){this.trieCache=null;for(const[t,r,s]of e)t===RC.Insert?this.entries.set(r,s):t===RC.Remove?this.entries.delete(r):E(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}const GC=(e,t,{typicalLength:r=32,compare:s=(e,r)=>{const s=t(e),i=t(r);return s<i?g.Less:s>i?g.Greater:g.Equal}}={})=>Ce.new(`Map<${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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=new Map,n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${t(a)}" >= "${t(n)}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)}),jC=Be.object({hash:Be.bytes(Pe).asOpaque(),length:Be.u32,slots:ke(Be.sequenceVarLen(Be.u32.asOpaque())).convert(R,iC)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new nC(e,t,r)),qC=Be.object({key:Be.bytes(Pe).asOpaque(),data:Be.sequenceVarLen(jC)}),zC=Be.sequenceVarLen(qC).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=pt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class WC extends vC{static Codec=Be.Class(WC,{serviceId:Be.u32.asOpaque(),data:Be.object({info:tC.Codec,preimages:_t(rC.Codec,e=>e.hash),lookupHistory:zC,storage:GC(sC.Codec,e=>e.key.toString())})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new WC(e,t)}}var JC,YC,XC;Be.Class(wC,{authPools:xC.authPools.Codec,authQueues:xC.authQueues.Codec,recentBlocks:xC.recentBlocks.Codec,nextValidatorData:Hr(zE.Codec),epochRoot:Be.bytes(De).asOpaque(),sealingKeySeries:YE.Codec,ticketsAccumulator:ke(Be.sequenceVarLen(Ot.Codec)).convert(e=>e,mt),disputesRecords:xC.disputesRecords.Codec,entropy:xC.entropy.Codec,designatedValidatorData:xC.designatedValidators.Codec,currentValidatorData:xC.currentValidators.Codec,previousValidatorData:xC.previousValidators.Codec,availabilityAssignment:xC.availabilityAssignment.Codec,timeslot:xC.timeslot.Codec,privilegedServices:xC.privilegedServices.Codec,statistics:xC.statistics.Codec,accumulationQueue:xC.accumulationQueue.Codec,recentlyAccumulated:xC.recentlyAccumulated.Codec,accumulationOutputLog:xC.accumulationOutputLog.Codec,services:Be.dictionary(Be.u32.asOpaque(),WC.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(JC||(JC={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(YC||(YC={}));class ZC{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return D.error(YC.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new VS(t.raw);if(e.getNodeType()===HS.Branch)return D.error(YC.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return D.ok(new ZC(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=vt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:XC.EmbeddedValue,value:e.getValue()}:{kind:XC.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===XC.EmbeddedValue?t.value:t.kind===XC.DbKey?P.blobFrom(this.db.get(t.key)):void E(t)}getStateRoot(){return LC.computeStateRoot(FC,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(XC||(XC={}));class ek{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){return await this.updateAndCommit(e,It.fromArray(PC,[]),Array.from(t,e=>[RC.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===RC.Insert){const e=LC.constructLeaf(FC,i.asOpaque(),n);t.replace(e),e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else if(e===RC.Remove){const e=LC.constructLeaf(FC,i.asOpaque(),P.empty());t.removeOne(e)}else E(e);const i=P.blobFromParts(t.array.map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),a=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([a,n])}catch(e){return console.error(e),D.error(JC.Commit)}return D.ok(O)}async updateAndSetState(e,t,r){const s=It.fromSortedArray(PC,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[RC.Insert,r.key,Ae.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,xC.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,xC.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,xC.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return XE.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,xC.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,xC.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,xC.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,xC.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,xC.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,xC.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,xC.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,xC.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,xC.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,xC.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,xC.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,xC.recentlyAccumulated))}(e,t);const r=(t,r)=>Ae.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=xC.serviceData(s);if(yield[RC.Insert,e.key,t(e.Codec,r.account)],r.kind===oC.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=xC.serviceLookupHistory(s,e.hash,e.length);yield[RC.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 aC.Provide:{const{hash:e,blob:i}=r.preimage,n=xC.servicePreimages(s,e);if(yield[RC.Insert,n.key,i],null!==r.slot){const n=xC.serviceLookupHistory(s,e,ne(i.length));yield[RC.Insert,n.key,t(n.Codec,iC([r.slot]))]}break}case aC.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,a=xC.serviceLookupHistory(s,e,i);yield[RC.Insert,a.key,t(a.Codec,n)];break}case aC.Remove:{const{hash:e,length:t}=r,i=xC.servicePreimages(s,e);yield[RC.Remove,i.key,OC];const n=xC.serviceLookupHistory(s,e,t);yield[RC.Remove,n.key,OC];break}default:E(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case cC.Set:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.storage.key:UC(r,t.storage.key),s=xC.serviceStorage(r,e);yield[RC.Insert,s.key,t.storage.value];break}case cC.Remove:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.key:UC(r,t.key),s=xC.serviceStorage(r,e);yield[RC.Remove,s.key,OC];break}default:E(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=xC.serviceData(t);yield[RC.Remove,e.key,OC]}}(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=ZC.fromLeavesBlob(P.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${P.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${N(s)}`);return TC.new(this.spec,s.ok)}}const tk=2**32,rk=Zs.new(void 0,"state-machine/port");class sk{port;listeners=new Gn.EventEmitter;responseListeners=new Gn.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw rk.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)%tk,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(ik(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){w("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 rk.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":w(-1!==this.responseListeners.eventNames().indexOf(ik(e.id))),this.responseListeners.emit(ik(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 ik(e){return`req:${e}`}const nk=Zs.new(void 0,"state-machine"),ak="channel";class ok{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 nk.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 nk.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),a=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!a)return this.port.respond(s.stateName,r,n.response);nk.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 nk.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new vE.MessageChannel,s=new sk(r.port2),i=e.currentState().stateName,[n,a]=s.prepareRequest(i,ak,r.port1);t.postMessage(n,[r.port1]);try{await a}catch(e){nk.error(JSON.stringify(e))}return new ok(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{w("request"===t.kind,"The initial message should be a request with channel."),w(t.name===ak),w(t.data instanceof vE.MessagePort);const s=new sk(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new ok(e,s)}}const ck=Symbol(),lk=Symbol();class dk{emitter=new Gn.EventEmitter;emit(e){this.emitter.emit(ck,e)}on(e){return this.emitter.on(ck,e),this}off(e){return this.emitter.off(ck,e),this}once(e){return this.emitter.once(ck,e),this}onceDone(e){return this.emitter.once(lk,e),this}markDone(){this.emitter.emit(lk),this.emitter.removeAllListeners(ck),this.emitter.removeAllListeners(lk)}}class uk{name;state;allStates;stateListeners=new Gn.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 w(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 hk=Zs.new(void 0,"state-machine/state");class fk{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){hk.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 gk extends fk{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class pk extends fk{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 bk extends fk{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 mk(e,t,r,s){const i=new vE.Worker(e),n=function(e,t,r){const s=new pk(t),i=new gk;return new uk(e,s,[s,r,i])}(`main->${r}`,r,s),a=await ok.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${a.currentState()}`),a}const yk=4294967295,Ak=4294967296,Ik=4096,vk=(w(!0,"incorrect minimal allocation shift"),7),wk=Ik>>vk,Sk=1048575,Ek=1048576,Ck=e=>S(e,e>=0&&e<=yk,`Incorrect memory index: ${e}!`),kk=e=>S(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var xk,Bk;(Bk=xk||(xk={}))[Bk.OK=255]="OK",Bk[Bk.HALT=0]="HALT",Bk[Bk.PANIC=1]="PANIC",Bk[Bk.FAULT=2]="FAULT",Bk[Bk.HOST=3]="HOST",Bk[Bk.OOG=4]="OOG";const _k=e=>S(e,e>=0&&e<=13,`Incorrect register index: ${e}!`);class Rk{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,w(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 w(104===e.length,"Invalid size of registers array."),new Rk(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]=Ok(t)}setI32(e,t){this.asSigned[e]=Ok(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 Ok(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}const Uk=e=>ne(e);var Tk,Nk;function Dk(...e){return e.map(_k)}!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(Tk||(Tk={}));class Mk{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return w(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 Mk(J.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"}(Nk||(Nk={}));class Pk{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 Lk{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 Hk{nibblesDecoder=new Lk;offsetDecoder=new Pk;code=new Uint8Array;mask=Mk.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 Nk.NO_ARGUMENTS:break;case Nk.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case Nk.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 Nk.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 Nk.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,a=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,a));const o=e+2+i,c=o+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(o,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Nk.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 Nk.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Nk.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const a=this.offsetDecoder.getSigned();t.nextPc=e+a;break}case Nk.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)),a=this.code.subarray(i,n);t.immediateDecoder.setBytes(a);break}case Nk.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Nk.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,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Nk.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(),a=e+3,o=a+n,c=this.code.subarray(a,o);t.firstImmediateDecoder.setBytes(c);const l=o,d=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,d);t.secondImmediateDecoder.setBytes(u);break}case Nk.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 Vk{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 Kk=Object.keys(Nk).length/2;var Qk;!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"}(Qk||(Qk={}));const Fk=Qk.MIN_U,$k=(()=>{const e=new Array(Fk+1);return e[Qk.TRAP]=Nk.NO_ARGUMENTS,e[Qk.FALLTHROUGH]=Nk.NO_ARGUMENTS,e[Qk.ECALLI]=Nk.ONE_IMMEDIATE,e[Qk.LOAD_IMM_64]=Nk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[Qk.STORE_IMM_U8]=Nk.TWO_IMMEDIATES,e[Qk.STORE_IMM_U16]=Nk.TWO_IMMEDIATES,e[Qk.STORE_IMM_U32]=Nk.TWO_IMMEDIATES,e[Qk.STORE_IMM_U64]=Nk.TWO_IMMEDIATES,e[Qk.JUMP]=Nk.ONE_OFFSET,e[Qk.JUMP_IND]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_U8]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_I8]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_U16]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_I16]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_U32]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_I32]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.LOAD_U64]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.STORE_U8]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.STORE_U16]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.STORE_U32]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.STORE_U64]=Nk.ONE_REGISTER_ONE_IMMEDIATE,e[Qk.STORE_IMM_IND_U8]=Nk.ONE_REGISTER_TWO_IMMEDIATES,e[Qk.STORE_IMM_IND_U16]=Nk.ONE_REGISTER_TWO_IMMEDIATES,e[Qk.STORE_IMM_IND_U32]=Nk.ONE_REGISTER_TWO_IMMEDIATES,e[Qk.STORE_IMM_IND_U64]=Nk.ONE_REGISTER_TWO_IMMEDIATES,e[Qk.LOAD_IMM_JUMP]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_EQ_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_NE_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_LT_U_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_LE_U_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_GE_U_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_GT_U_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_LT_S_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_LE_S_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_GE_S_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.BRANCH_GT_S_IMM]=Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Qk.MOVE_REG]=Nk.TWO_REGISTERS,e[Qk.SBRK]=Nk.TWO_REGISTERS,e[Qk.COUNT_SET_BITS_64]=Nk.TWO_REGISTERS,e[Qk.COUNT_SET_BITS_32]=Nk.TWO_REGISTERS,e[Qk.LEADING_ZERO_BITS_64]=Nk.TWO_REGISTERS,e[Qk.LEADING_ZERO_BITS_32]=Nk.TWO_REGISTERS,e[Qk.TRAILING_ZERO_BITS_64]=Nk.TWO_REGISTERS,e[Qk.TRAILING_ZERO_BITS_32]=Nk.TWO_REGISTERS,e[Qk.SIGN_EXTEND_8]=Nk.TWO_REGISTERS,e[Qk.SIGN_EXTEND_16]=Nk.TWO_REGISTERS,e[Qk.ZERO_EXTEND_16]=Nk.TWO_REGISTERS,e[Qk.REVERSE_BYTES]=Nk.TWO_REGISTERS,e[Qk.STORE_IND_U8]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.STORE_IND_U16]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.STORE_IND_U32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.STORE_IND_U64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_U8]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_I8]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_U16]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_I16]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_U32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_I32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.LOAD_IND_U64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ADD_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ADD_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.AND_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.XOR_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.OR_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.MUL_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.MUL_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SET_LT_U_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SET_LT_S_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_L_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_R_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHAR_R_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.NEG_ADD_IMM_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_L_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_R_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHAR_R_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.NEG_ADD_IMM_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SET_GT_U_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SET_GT_S_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_L_IMM_ALT_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_R_IMM_ALT_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHAR_R_IMM_ALT_32]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_L_IMM_ALT_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHLO_R_IMM_ALT_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.SHAR_R_IMM_ALT_64]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.CMOV_IZ_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.CMOV_NZ_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ROT_R_64_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ROT_R_64_IMM_ALT]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ROT_R_32_IMM]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.ROT_R_32_IMM_ALT]=Nk.TWO_REGISTERS_ONE_IMMEDIATE,e[Qk.BRANCH_EQ]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.BRANCH_NE]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.BRANCH_LT_U]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.BRANCH_LT_S]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.BRANCH_GE_U]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.BRANCH_GE_S]=Nk.TWO_REGISTERS_ONE_OFFSET,e[Qk.LOAD_IMM_JUMP_IND]=Nk.TWO_REGISTERS_TWO_IMMEDIATES,e[Qk.ADD_32]=Nk.THREE_REGISTERS,e[Qk.ADD_64]=Nk.THREE_REGISTERS,e[Qk.SUB_32]=Nk.THREE_REGISTERS,e[Qk.SUB_64]=Nk.THREE_REGISTERS,e[Qk.AND]=Nk.THREE_REGISTERS,e[Qk.XOR]=Nk.THREE_REGISTERS,e[Qk.OR]=Nk.THREE_REGISTERS,e[Qk.MUL_32]=Nk.THREE_REGISTERS,e[Qk.MUL_64]=Nk.THREE_REGISTERS,e[Qk.MUL_UPPER_S_S]=Nk.THREE_REGISTERS,e[Qk.MUL_UPPER_U_U]=Nk.THREE_REGISTERS,e[Qk.MUL_UPPER_S_U]=Nk.THREE_REGISTERS,e[Qk.DIV_U_32]=Nk.THREE_REGISTERS,e[Qk.DIV_S_32]=Nk.THREE_REGISTERS,e[Qk.REM_U_32]=Nk.THREE_REGISTERS,e[Qk.REM_S_32]=Nk.THREE_REGISTERS,e[Qk.DIV_U_64]=Nk.THREE_REGISTERS,e[Qk.DIV_S_64]=Nk.THREE_REGISTERS,e[Qk.REM_U_64]=Nk.THREE_REGISTERS,e[Qk.REM_S_64]=Nk.THREE_REGISTERS,e[Qk.SET_LT_U]=Nk.THREE_REGISTERS,e[Qk.SET_LT_S]=Nk.THREE_REGISTERS,e[Qk.SHLO_L_32]=Nk.THREE_REGISTERS,e[Qk.SHLO_R_32]=Nk.THREE_REGISTERS,e[Qk.SHAR_R_32]=Nk.THREE_REGISTERS,e[Qk.SHLO_L_64]=Nk.THREE_REGISTERS,e[Qk.SHLO_R_64]=Nk.THREE_REGISTERS,e[Qk.SHAR_R_64]=Nk.THREE_REGISTERS,e[Qk.CMOV_IZ]=Nk.THREE_REGISTERS,e[Qk.CMOV_NZ]=Nk.THREE_REGISTERS,e[Qk.ROT_L_64]=Nk.THREE_REGISTERS,e[Qk.ROT_L_32]=Nk.THREE_REGISTERS,e[Qk.ROT_R_64]=Nk.THREE_REGISTERS,e[Qk.ROT_R_32]=Nk.THREE_REGISTERS,e[Qk.AND_INV]=Nk.THREE_REGISTERS,e[Qk.OR_INV]=Nk.THREE_REGISTERS,e[Qk.XNOR]=Nk.THREE_REGISTERS,e[Qk.MAX]=Nk.THREE_REGISTERS,e[Qk.MAX_U]=Nk.THREE_REGISTERS,e[Qk.MIN]=Nk.THREE_REGISTERS,e[Qk.MIN_U]=Nk.THREE_REGISTERS,e})(),Gk=e=>ne(e),jk=e=>oe(e),qk=e=>"number"==typeof e&&e<2**32?Gk(e):jk(e);function zk(e){return new Wk(oe(e))}class Wk{gas;constructor(e){this.gas=e}set(e){this.gas=oe(e)}get(){return qk(this.gas)}sub(e){const t=this.gas-oe(e);return t>=0n?(this.gas=oe(t),!1):(this.gas=oe(0n),!0)}}const Jk=[[Qk.TRAP,1],[Qk.FALLTHROUGH,1],[Qk.ECALLI,v.isSuite(f.JAMDUNA,h.V0_6_5)?0:1],[Qk.LOAD_IMM_64,1],[Qk.STORE_IMM_U8,1],[Qk.STORE_IMM_U16,1],[Qk.STORE_IMM_U32,1],[Qk.STORE_IMM_U64,1],[Qk.JUMP,1],[Qk.JUMP_IND,1],[Qk.LOAD_IMM,1],[Qk.LOAD_U8,1],[Qk.LOAD_I8,1],[Qk.LOAD_U16,1],[Qk.LOAD_I16,1],[Qk.LOAD_U32,1],[Qk.LOAD_I32,1],[Qk.LOAD_U64,1],[Qk.STORE_U8,1],[Qk.STORE_U16,1],[Qk.STORE_U32,1],[Qk.STORE_U64,1],[Qk.STORE_IMM_IND_U8,1],[Qk.STORE_IMM_IND_U16,1],[Qk.STORE_IMM_IND_U32,1],[Qk.STORE_IMM_IND_U64,1],[Qk.LOAD_IMM_JUMP,1],[Qk.BRANCH_EQ_IMM,1],[Qk.BRANCH_NE_IMM,1],[Qk.BRANCH_LT_U_IMM,1],[Qk.BRANCH_LE_U_IMM,1],[Qk.BRANCH_GE_U_IMM,1],[Qk.BRANCH_GT_U_IMM,1],[Qk.BRANCH_LT_S_IMM,1],[Qk.BRANCH_LE_S_IMM,1],[Qk.BRANCH_GE_S_IMM,1],[Qk.BRANCH_GT_S_IMM,1],[Qk.MOVE_REG,1],[Qk.SBRK,1],[Qk.COUNT_SET_BITS_64,1],[Qk.COUNT_SET_BITS_32,1],[Qk.LEADING_ZERO_BITS_64,1],[Qk.LEADING_ZERO_BITS_32,1],[Qk.TRAILING_ZERO_BITS_64,1],[Qk.TRAILING_ZERO_BITS_32,1],[Qk.SIGN_EXTEND_8,1],[Qk.SIGN_EXTEND_16,1],[Qk.ZERO_EXTEND_16,1],[Qk.REVERSE_BYTES,1],[Qk.STORE_IND_U8,1],[Qk.STORE_IND_U16,1],[Qk.STORE_IND_U32,1],[Qk.STORE_IND_U64,1],[Qk.LOAD_IND_U8,1],[Qk.LOAD_IND_I8,1],[Qk.LOAD_IND_U16,1],[Qk.LOAD_IND_I16,1],[Qk.LOAD_IND_U32,1],[Qk.LOAD_IND_I32,1],[Qk.LOAD_IND_U64,1],[Qk.ADD_IMM_32,1],[Qk.AND_IMM,1],[Qk.XOR_IMM,1],[Qk.OR_IMM,1],[Qk.MUL_IMM_32,1],[Qk.SET_LT_U_IMM,1],[Qk.SET_LT_S_IMM,1],[Qk.SHLO_L_IMM_32,1],[Qk.SHLO_R_IMM_32,1],[Qk.SHAR_R_IMM_32,1],[Qk.NEG_ADD_IMM_32,1],[Qk.SET_GT_U_IMM,1],[Qk.SET_GT_S_IMM,1],[Qk.SHLO_L_IMM_ALT_32,1],[Qk.SHLO_R_IMM_ALT_32,1],[Qk.SHAR_R_IMM_ALT_32,1],[Qk.CMOV_IZ_IMM,1],[Qk.CMOV_NZ_IMM,1],[Qk.ADD_IMM_64,1],[Qk.MUL_IMM_64,1],[Qk.SHLO_L_IMM_64,1],[Qk.SHLO_R_IMM_64,1],[Qk.SHAR_R_IMM_64,1],[Qk.NEG_ADD_IMM_64,1],[Qk.SHLO_L_IMM_ALT_64,1],[Qk.SHLO_R_IMM_ALT_64,1],[Qk.SHAR_R_IMM_ALT_64,1],[Qk.ROT_R_64_IMM,1],[Qk.ROT_R_64_IMM_ALT,1],[Qk.ROT_R_32_IMM,1],[Qk.ROT_R_32_IMM_ALT,1],[Qk.BRANCH_EQ,1],[Qk.BRANCH_NE,1],[Qk.BRANCH_LT_U,1],[Qk.BRANCH_LT_S,1],[Qk.BRANCH_GE_U,1],[Qk.BRANCH_GE_S,1],[Qk.LOAD_IMM_JUMP_IND,1],[Qk.ADD_32,1],[Qk.SUB_32,1],[Qk.MUL_32,1],[Qk.DIV_U_32,1],[Qk.DIV_S_32,1],[Qk.REM_U_32,1],[Qk.REM_S_32,1],[Qk.SHLO_L_32,1],[Qk.SHLO_R_32,1],[Qk.SHAR_R_32,1],[Qk.ADD_64,1],[Qk.SUB_64,1],[Qk.MUL_64,1],[Qk.DIV_U_64,1],[Qk.DIV_S_64,1],[Qk.REM_U_64,1],[Qk.REM_S_64,1],[Qk.SHLO_L_64,1],[Qk.SHLO_R_64,1],[Qk.SHAR_R_64,1],[Qk.AND,1],[Qk.XOR,1],[Qk.OR,1],[Qk.MUL_UPPER_S_S,1],[Qk.MUL_UPPER_U_U,1],[Qk.MUL_UPPER_S_U,1],[Qk.SET_LT_U,1],[Qk.SET_LT_S,1],[Qk.CMOV_IZ,1],[Qk.CMOV_NZ,1],[Qk.ROT_L_64,1],[Qk.ROT_L_32,1],[Qk.ROT_R_64,1],[Qk.ROT_R_32,1],[Qk.AND_INV,1],[Qk.OR_INV,1],[Qk.XNOR,1],[Qk.MAX,1],[Qk.MAX_U,1],[Qk.MIN,1],[Qk.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:Gk(t)}])(t);return e[r]=s,e},{}),Yk=(()=>{const e=new Array(Fk+1);return e.fill(!1),e[Qk.TRAP]=!0,e[Qk.FALLTHROUGH]=!0,e[Qk.JUMP]=!0,e[Qk.JUMP_IND]=!0,e[Qk.LOAD_IMM_JUMP]=!0,e[Qk.LOAD_IMM_JUMP_IND]=!0,e[Qk.BRANCH_EQ]=!0,e[Qk.BRANCH_NE]=!0,e[Qk.BRANCH_GE_U]=!0,e[Qk.BRANCH_GE_S]=!0,e[Qk.BRANCH_LT_U]=!0,e[Qk.BRANCH_LT_S]=!0,e[Qk.BRANCH_EQ_IMM]=!0,e[Qk.BRANCH_NE_IMM]=!0,e[Qk.BRANCH_LT_U_IMM]=!0,e[Qk.BRANCH_LT_S_IMM]=!0,e[Qk.BRANCH_LE_U_IMM]=!0,e[Qk.BRANCH_LE_S_IMM]=!0,e[Qk.BRANCH_GE_U_IMM]=!0,e[Qk.BRANCH_GE_S_IMM]=!0,e[Qk.BRANCH_GT_U_IMM]=!0,e[Qk.BRANCH_GT_S_IMM]=!0,e})();class Xk{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&Yk[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 Zk=(()=>{const e=new Array(Fk+1);for(let t=0;t<Fk+1;t++){const r=Jk[t]?.gas;e[t]=r}return e})();class ex{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const tx=e=>S(e,e>=0&&e<Ik,`Incorect page index: ${e}!`),rx=e=>S(e,e>=0&&e<=Sk,`Incorrect page number: ${e}!`);function sx(e){return rx(e===Sk?0:e+1)}function ix(e){return Ik*Math.ceil(e/Ik)}function nx(e){return rx(e>>>12)}function ax(e){return Ck(e>>>12<<12)}function ox(e){return Ck(e<<12>>>0)}class cx{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=ox(rx(e));return new cx(r,t)}static fromMemoryIndex(e,t=!1){const r=ax(Ck(e%Ak));return new cx(r,t)}}class lx extends Error{constructor(){super("Out of bounds")}}Error,Error;class dx extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class ux extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class hx extends Error{constructor(){super("You are trying to access reserved memory!")}}class fx extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class gx extends Error{constructor(){super("Out of memory")}}class px{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Ck((this.start+this.length)%Ak),t>0&&(this.lastIndex=Ck((this.end-1+Ak)%Ak))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Ak)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new px(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 bx=px.fromStartAndLength(Ck(0),65536);class mx{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=rx((this.start+this.length)%Ek)}static fromMemoryRange(e){const t=nx(e.start);if(e.isEmpty())return new mx(t,0);const r=nx(e.lastIndex??e.end),s=sx(r);if((t===s||t===r)&&e.length>Ik)return new mx(t,Ek);const i=t<s?s-t:Ek-t+s;return mx.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Ek)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new mx(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=sx(t)}while(t!==e)}}class yx{start;constructor(e){this.start=ox(e)}}class Ax extends yx{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Ik)return D.error(cx.fromMemoryIndex(this.start+Ik));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){return D.error(cx.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Ix extends yx{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Ik,Math.max(r,wk));this.buffer=new ArrayBuffer(s,{maxByteLength:Ik}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Ik)return D.error(cx.fromMemoryIndex(this.start+Ik));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Ik){const r=Math.min(Ik,Math.max(wk,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),D.ok(O)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Ik){const r=Math.min(Ik,Math.max(wk,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var vx;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(vx||(vx={}));class wx{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new wx(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=kk(bx.end),t=kk(bx.end),r=kk(yk),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=kk(bx.end),this.virtualSbrkIndex=kk(bx.end),this.endHeapIndex=kk(yk),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 D.ok(O);const r=this.getPages(e,t.length,vx.WRITE);if(r.isError)return D.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=tx(i%Ik),a=Math.min(Ik-s,n),o=i-e,c=t.subarray(o,o+a);r.storeFrom(s,c),i+=a,n-=a}return D.ok(O)}getPages(e,t,r){if(0===t)return D.ok([]);const s=px.fromStartAndLength(e,t),i=mx.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return D.error(cx.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return D.error(cx.fromPageNumber(e));if(r===vx.WRITE&&!t.isWriteable())return D.error(cx.fromPageNumber(e,!0));n.push(t)}return D.ok(n)}loadInto(e,t){if(0===e.length)return D.ok(O);const r=this.getPages(t,e.length,vx.READ);if(r.isError)return D.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=tx(i%Ik),a=Math.min(Ik-s,n),o=i-t,c=e.subarray(o);r.loadInto(c,s,a),i+=a,n-=a}return D.ok(O)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(yk<r+e||r+e>this.endHeapIndex)throw new gx;const s=kk(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=kk(ix(s)),n=nx(t),a=(i-t)/Ik,o=mx.fromStartAndLength(n,a);for(const e of o){const t=new Ix(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 Sx{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new ux}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(bx))throw new hx}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Ik===0,"start needs to be a multiple of page size (4096)"),w(t%Ik===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=px.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(mx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Ik,(e+1)*Ik),i=new Ax(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Ik===0,"start needs to be a multiple of page size (4096)"),w(t%Ik===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=px.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(mx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Ik,(e+1)*Ik),i=new Ix(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Ik-e%Ik;w(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=px.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=nx(e),a=this.initialMemory.get(n);if(void 0===a)throw new fx;const o=tx(e-a.start);return a.setData(o,t),this}finalize(e,t){w(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=px.fromStartAndLength(e,t-e),s=mx.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new dx;const i=wx.fromInitialMemory({memory:this.initialMemory,sbrkIndex:kk(e),endHeapIndex:t});return this.isFinalized=!0,i}}class Ex{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 Qk.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Qk.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class Cx{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,a,o){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=a,this.bitRotationOps=o}dispatch(e,t){switch(e){case Qk.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Qk.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Qk.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class kx{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 Qk.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Qk.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class xx{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case Qk.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case Qk.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Qk.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class Bx{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case Qk.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Qk.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Qk.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Qk.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Qk.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Qk.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class _x{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===Qk.JUMP&&this.branchOps.jump(t.nextPc)}}class Rx{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case Qk.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case Qk.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Qk.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class Ox{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Qk.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Qk.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Qk.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Qk.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class Ux{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Qk.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Qk.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Qk.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Qk.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class Tx{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case Qk.TRAP:this.noArgsOps.trap();break;case Qk.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class Nx{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case Qk.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 Dx{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===Qk.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class Mx{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===Qk.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class Px{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 Lx=4294967295,Hx=-(2**31),Vx=32,Kx=64n;function Qx(e,t){return e>Lx-t?Lx-(Lx-e+(Lx-t))-1:e+t}function Fx(e,t){return(e+t)%2n**64n}function $x(e,t){return t>e?Lx-t+e+1:e-t}function Gx(e,t){return(2n**64n+e-t)%2n**64n}function jx(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 qx(e,t){return e*t%2n**64n}function zx(e){return e>=1n<<63n?e-(1n<<64n):e}function Wx(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function Jx(e,t){return zx(0xffffffffffffffffn&e*t>>64n)}function Yx(e,t){w(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 Xx(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function Zx(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class eB{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%Vx)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%Kx)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%Vx)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,Yx(this.regs.getU64(e),this.regs.getU64(t)%Kx))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%Vx)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%Kx)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%Vx)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%Kx)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%Vx)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,Yx(this.regs.getU64(e),t.getU64()%Kx))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%Vx)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%Kx)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%Vx)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%Kx)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%Vx)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,Yx(t.getU64(),this.regs.getU64(e)%Kx))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%Vx)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%Kx)}}class tB{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,Ok(Qx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,Fx(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,Ok(Qx(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,Fx(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,Ok(jx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,qx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,Wx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,Jx(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,zx(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,Ok(jx(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,qx(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,Jx(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,Wx(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,Ok($x(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,Gx(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,Ok($x(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,Gx(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)===Hx?this.regs.setU64(r,Ok(this.regs.getLowerU32(e))):this.regs.setI64(r,Ok(~~(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,Ok(~~(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)===Hx?this.regs.setU64(r,0n):this.regs.setI64(r,Ok(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,Ok(this.regs.getLowerU32(e))):this.regs.setU64(r,Ok(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,Xx(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,Xx(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,Zx(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,Zx(this.regs.getU64(e),this.regs.getU64(t)))}}class rB{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 sB{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 iB,nB;(nB=iB||(iB={}))[nB.HALT=0]="HALT",nB[nB.PANIC=1]="PANIC",nB[nB.FAULT_ACCESS=2]="FAULT_ACCESS",nB[nB.FAULT=3]="FAULT",nB[nB.HOST=4]="HOST";class aB{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=iB.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 oB{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),Ck(e));i.isError?i.error.isAccessFault?this.instructionResult.status=iB.FAULT_ACCESS:(this.instructionResult.status=iB.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),Ck(e));i.isError?i.error.isAccessFault?this.instructionResult.status=iB.FAULT_ACCESS:(this.instructionResult.status=iB.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=Qx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class cB{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=Qx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=Qx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=Qx(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=Qx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=Qx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=Qx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=Qx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Ck(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=iB.FAULT_ACCESS:(this.instructionResult.status=iB.FAULT,this.instructionResult.exitParam=ax(r.error.address)))}}class lB{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=iB.PANIC}fallthrough(){}}class dB{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=iB.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=iB.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=iB.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=iB.PANIC}caluclateJumpAddress(e,t){return Qx(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class uB{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=iB.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class hB{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=iB.FAULT}}}class fB{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|Yx(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(Yx(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 gB{indices;constructor(e,t){w(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 gB(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const pB=Zs.new(void 0,"pvm-interpreter");var bB;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(bB||(bB={}));class mB{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 Mk(r),this.jumpTable=new gB(i,s)}decodeProgram(e){const t=fe.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,a=t.bytes(n).raw,o=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:o,jumpTableItemLength:s,jumpTable:a}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return D.ok(new mB(e))}catch(e){return pB.error(`Invalid program: ${e}`),D.error(bB.InvalidProgramError)}}}class yB{useSbrkGas;ignoreInstructionGas;registers=new Rk;code=new Uint8Array;mask=Mk.empty();pc=0;gas=zk(qk(0));initialGas=zk(qk(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new ex;memory=new wx;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=xk.OK;argsDecodingResults=(()=>{const e=new Array(Kk);return e[Nk.NO_ARGUMENTS]={type:Nk.NO_ARGUMENTS,noOfBytesToSkip:1},e[Nk.ONE_IMMEDIATE]={type:Nk.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new Pk},e[Nk.TWO_REGISTERS]={type:Nk.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[Nk.THREE_REGISTERS]={type:Nk.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Pk,nextPc:0},e[Nk.TWO_REGISTERS_ONE_OFFSET]={type:Nk.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[Nk.TWO_REGISTERS_ONE_IMMEDIATE]={type:Nk.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new Pk},e[Nk.ONE_REGISTER_ONE_IMMEDIATE]={type:Nk.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Pk},e[Nk.ONE_REGISTER_TWO_IMMEDIATES]={type:Nk.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new Pk,secondImmediateDecoder:new Pk},e[Nk.ONE_OFFSET]={type:Nk.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[Nk.TWO_IMMEDIATES]={type:Nk.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Pk,secondImmediateDecoder:new Pk},e[Nk.TWO_REGISTERS_TWO_IMMEDIATES]={type:Nk.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Pk,secondImmediateDecoder:new Pk,firstRegisterIndex:0,secondRegisterIndex:0},e[Nk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:Nk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new Vk},e})();basicBlocks;jumpTable=gB.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new Hk,this.basicBlocks=new Xk;const r=new tB(this.registers),s=new eB(this.registers),i=new Px(this.registers),n=new rB(this.registers),a=new sB(this.registers),o=new aB(this.registers,this.instructionResult,this.basicBlocks),c=new oB(this.registers,this.memory,this.instructionResult),l=new cB(this.registers,this.memory,this.instructionResult),d=new lB(this.instructionResult),u=new dB(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),h=new uB(this.instructionResult),f=new hB(this.registers,this.memory,this.instructionResult),g=new fB(this.registers);this.threeRegsDispatcher=new Ex(r,s,i,n,a,g),this.twoRegsOneImmDispatcher=new Cx(r,s,i,n,a,l,c,g),this.twoRegsDispatcher=new kx(a,f,i,g),this.oneRegOneImmOneOffsetDispatcher=new xx(o,c),this.twoRegsOneOffsetDispatcher=new Bx(o),this.oneOffsetDispatcher=new _x(o),this.oneRegOneImmDispatcher=new Rx(c,l,u),this.twoImmsDispatcher=new Ux(l),this.oneRegTwoImmsDispatcher=new Ox(l),this.noArgsDispatcher=new Tx(d),this.twoRegsTwoImmsDispatcher=new Nx(c,u),this.oneImmDispatcher=new Dx(h),this.oneRegOneExtImmDispatcher=new Mx(c)}reset(e,t,r,s,i){const n=new mB(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=zk(r),this.initialGas=zk(r),this.status=xk.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([Qk[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===xk.OK;);}nextStep(){this.status===xk.HOST&&(this.status=xk.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??Qk.TRAP,t=void 0!==Qk[e],r=Zk[e]??Zk[Qk.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=xk.OOG,this.status;const s=$k[e]??Nk.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 Nk.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case Nk.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case Nk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case Nk.TWO_REGISTERS:if(this.useSbrkGas&&e===Qk.SBRK){const e=e=>ix(e)/Ik*16;if(this.gas.sub(qk(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=xk.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case Nk.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case Nk.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case Nk.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case Nk.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case Nk.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case Nk.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case Nk.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case Nk.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case Nk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=iB.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==iB.FAULT&&this.instructionResult.status!==iB.FAULT_ACCESS||this.gas.sub(Zk[Qk.TRAP]),this.instructionResult.status){case iB.FAULT:this.status=xk.FAULT;break;case iB.HALT:this.status=xk.HALT;break;case iB.PANIC:case iB.FAULT_ACCESS:this.status=xk.PANIC;break;case iB.HOST:this.status=xk.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=jk(this.initialGas.get())-jk(this.gas.get());return e<0?this.initialGas.get():jk(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?ne(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(rx(e))}}class AB{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?D.ok(O):e+oe(t.length)>Ak?D.error(new lx):this.memory.storeFrom(Ck(Number(e)),t)}loadInto(e,t){return 0===e.length?D.ok(O):t+oe(e.length)>Ak?D.error(new lx):this.memory.loadInto(e,Ck(Number(t)))}getMemory(){return this.memory}}class IB{registers;constructor(e){this.registers=e}get(e){return oe(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class vB{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,w(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 vB(e,t,null)}static fromMemorySlice(e,t){return new vB(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class wB{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===xk.OOG)return vB.fromStatus(r,e);if(e===xk.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),a=new Uint8Array(n),o=Ck(i);return e.loadInto(a,o).isError?vB.fromMemorySlice(r,new Uint8Array):vB.fromMemorySlice(r,a)}return vB.fromStatus(r,xk.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==xk.HOST)return this.getReturnValue(t,e);w(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 IB(e.getRegisters()),n=new AB(e.getMemory()),a=Uk(r),o=this.hostCalls.get(a),c=s.get(),l="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(l))return this.hostCalls.traceHostCall("OOG",a,o,i,s.get()),vB.fromStatus(e.getGasConsumed(),xk.OOG);this.hostCalls.traceHostCall("Invoking",a,o,i,c);const d=await o.execute(s,i,n);if(this.hostCalls.traceHostCall(void 0===d?"Result":`Status(${d})`,a,o,i,s.get()),d===Tk.Halt)return t=xk.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 SB{instances=[];waitingQueue=[];constructor(e){const t=v.isGreaterOrEqual(h.V0_6_7)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.W3F_DAVXY,h.V0_6_6);for(let r=0;r<e;r++)this.instances.push(new yB({useSbrkGas:!1,ignoreInstructionGas:!t}))}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 EB={NONE:oe(0xffffffffffffffffn),WHAT:oe(0xfffffffffffffffen),OOB:oe(0xfffffffffffffffdn),WHO:oe(0xfffffffffffffffcn),FULL:oe(0xfffffffffffffffbn),CORE:oe(0xfffffffffffffffan),CASH:oe(0xfffffffffffffff9n),LOW:oe(0xfffffffffffffff8n),HUH:oe(0xfffffffffffffff7n),OK:oe(0n)},CB=ne(2**32-1),kB=oe(CB),xB=Nr(2**32-1);function BB(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:_B(s)}function _B(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?Nr(t):null}function RB(e){return e>kB?CB:ne(Number(e))}const OB=Zs.new(void 0,"host-calls");class UB{hostCalls=new Map;missing=new TB;constructor(...e){for(const t of e)w(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){return this.hostCalls.get(e)??this.missing}traceHostCall(e,t,r,s,i){const{currentServiceId:n}=r,a=t!==r.index?` (${t})`:"",o=`${r.constructor.name}:${r.index}`,c=r.tracedRegisters.map(e=>[e.toString().padStart(2,"0"),s.get(e)]).filter(e=>0n!==e[1]).map(([e,t])=>`r${e}=${t} (0x${t.toString(16)})`).join(", ");OB.trace(`[${n}] ${e} ${o}${a}. Gas: ${i}. Regs: ${c}.`)}}class TB{index=Uk(2**32-1);gasCost=Gk(10);currentServiceId=xB;tracedRegisters=Dk(7);execute(e,t,r){return t.set(7,EB.WHAT),Promise.resolve(void 0)}}const NB=4096,DB=65536,MB=2**24,PB=4278059008,LB=4278124544;function HB(e){return NB*Math.ceil(e/NB)}class VB extends B{start;end;data;static from({start:e,end:t,data:r}){return new VB(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class KB extends B{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class QB extends B{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function FB(e,t,r=null){return new VB(e,t,r)}class $B{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?GB(e):{code:e},{code:n,memory:a,registers:o}=function(e,t){const r=fe.fromBlob(e),s=r.u24(),i=r.u24(),n=S(t.length,t.length<=MB,"Incorrect arguments length"),a=S(s,s<=MB,"Incorrect readonly segment length"),o=S(i,i<=MB,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),d=r.bytes(a).raw,u=r.bytes(o).raw,h=r.u32(),f=r.bytes(h).raw;r.finish();const g=DB+HB(a),p=131072+(b=a,DB*Math.ceil(b/DB));var b;const m=p+HB(o),y=p+HB(o)+c*NB,A=PB-HB(l),I=PB,v=LB,w=v+HB(n),E=w+HB(n);function C(e){return!1!==e}const k=[a>0&&FB(65536,g,d),n>0&&FB(v,w,t),w<E&&FB(w,E)].filter(C),x=[o>0&&FB(p,m,u),m<y&&FB(m,y),A<I&&FB(A,I)].filter(C);return new QB(f,new KB(k,x,y,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(PB),t[7]=BigInt(LB),t[8]=BigInt(e),t}(t.length))}(s,t),c=new Rk;c.copyFrom(o);const l=new Sx;for(const{start:e,end:t,data:r}of a.readable){const s=Ck(e),i=Ck(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of a.writeable){const s=Ck(e),i=Ck(t);l.setWriteablePages(s,i,r??new Uint8Array)}const d=Ck(a.sbrkIndex),u=kk(a.heapEnd),h=l.finalize(d,u);return new $B(n,c,h,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?GB(e):{code:e},i=new Rk,n=new wx;return new $B(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function GB(e){const t=fe.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var jB,qB,zB;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(jB||(jB={}));class WB{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return gt(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return gt(this.keccakHasher,[e,t,r])}header(e){return new He(qe(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=qe(e.report.encoded(),this.allocator).asOpaque();return P.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=Ae.encodeObject(Be.sequenceVarLen(_C),t,this.context),s=qe(e.tickets.encoded(),this.allocator).asOpaque(),i=qe(e.preimages.encoded(),this.allocator).asOpaque(),n=qe(r,this.allocator).asOpaque(),a=qe(e.assurances.encoded(),this.allocator).asOpaque(),o=qe(e.disputes.encoded(),this.allocator).asOpaque(),c=P.blobFromParts([s.raw,i.raw,n.raw,a.raw,o.raw]);return new Ve(qe(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Wr.Codec,e)}encode(e,t){const r=Ae.encodeObject(e,t,this.context);return new Ve(qe(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(qB||(qB={}));class JB{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 D.error(qB.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=qe(i).asOpaque(),a=this.state.getService(t);if(null===a)return D.error(qB.AccountNotFound);const o=a.hasPreimage(n),c=a.getLookupHistory(n,ne(i.length));if(o||null===c||!nC.isRequested(c))return D.error(qB.PreimageUnneeded);s.push(lC.provide({serviceId:t,preimage:rC.create({hash:n,blob:i}),slot:r}))}return D.ok({preimages:s})}}class YB{spec;importer;toImport=At.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?g.Greater:r>0?g.Less:g.Equal});queuedBlocks=bt.new();lastEpoch=Pr(2**32-1);constructor(e,t){this.spec=e,this.importer=t}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))}static getBlockDetails(e){let t,r;try{t=e.header.encoded(),r=e.header.view().timeSlotIndex.materialize()}catch{return D.error("invalid")}const s=qe(t).asOpaque();return D.ok(new He(s,{block:e,timeSlot:r}))}push(e){const t=e.hash;if(this.queuedBlocks.has(t))return D.error("already queued");const{timeSlot:r,block:s}=e.data,i={headerHash:t,timeSlot:r,block:s,seal:this.isCurrentEpoch(r)?this.importer.preverifySeal(r,s):Promise.resolve(null)};return this.toImport.insert(i),this.queuedBlocks.insert(t),D.ok(O)}shift(){const e=this.toImport.pop();if(void 0!==e){this.queuedBlocks.delete(e.headerHash);const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=Pr(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"}(zB||(zB={}));const XB=L.zero(Pe).asOpaque();class ZB{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 D.error(zB.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(XB)){const e=this.blocks.getHeader(s);if(null===e)return D.error(zB.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return D.error(zB.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 D.error(zB.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const a=t.priorStateRoot.materialize(),o=this.blocks.getPostStateRoot(s);return null===o?D.error(zB.StateRootNotFound,`Posterior state root ${s.toString()} not found`):a.isEqualTo(o)?D.ok(r.hash):D.error(zB.InvalidStateRoot,`Invalid prior state root: ${a.toString()}, expected ${o.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var e_;function t_(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"}(e_||(e_={}));const r_=P.blobFromString("jam_valid").raw,s_=P.blobFromString("jam_invalid").raw,i_=P.blobFromString("jam_guarantee").raw;function n_({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:P.blobFromParts(i_,r.raw)}}function a_({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?r_:s_;return{key:s,signature:r,message:P.blobFromParts(i,e.raw)}}function o_(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?r_:s_;return{key:r,signature:i,message:P.blobFromParts(n,t.raw)}}class c_{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!t_(e.culprits,"key"))return D.error(e_.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(e_.OffenderAlreadyReported);if(!s.has(i))return D.error(e_.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(a))return D.error(e_.CulpritsVerdictNotBad);const o=r.culprits[n];if(!o?.isValid)return D.error(e_.BadSignature)}return D.ok(null)}verifyFaults(e,t,r,s){if(!t_(e.faults,"key"))return D.error(e_.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a,wasConsideredValid:o}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(e_.OffenderAlreadyReported);if(!s.has(i))return D.error(e_.BadAuditorKey);if(o){const e=t.toAddToGoodSet.findExact(a),r=t.toAddToBadSet.findExact(a);if(void 0!==e||void 0===r)return D.error(e_.FaultVerdictWrong)}if(!r.faults[n].isValid)return D.error(e_.BadSignature)}return D.ok(null)}verifyVerdicts(e,t){if(!t_(e.verdicts,"workReportHash"))return D.error(e_.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 D.error(e_.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 D.error(e_.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 D.error(e_.BadValidatorIndex);if(!t.judgements[s].isValid)return D.error(e_.BadSignature);s+=1}}return D.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 D.error(e_.AlreadyJudged)}return D.ok(null)}calculateVotesForWorkReports(e){const t=pt.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 D.error(e_.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 D.error(e_.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return D.error(e_.BadVoteSplit);return D.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:It.fromArrayUnique(ME,t),toAddToBadSet:It.fromArrayUnique(ME,r),toAddToWonkySet:It.fromArrayUnique(ME,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 OE(t,this.chainSpec)}getOffenders(e){const t=bt.new();for(const{key:r}of e.culprits)t.insert(r);for(const{key:r}of e.faults)t.insert(r);return t}getUpdatedDisputesRecords(e,t){const r=At.fromArray(ME,Array.from(t));return DE.create({goodSet:It.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:It.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:It.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:It.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 D.error(e_.BadValidatorIndex);const i=s.ed25519;t.judgements.push(o_(r,n,i))}}return t.culprits=e.culprits.map(n_),t.faults=e.faults.map(a_),D.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 bt.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return D.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 wr(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,a=this.getValidatorKeys(),o=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,a),this.verifyFaults(e,i,n,a),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(o?.isError)return D.error(o.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),d=this.getClearedCoreAssignment(s);return D.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:d}})}}const l_=P.blobFromString("jam_entropy").raw,d_=P.blobFromString("jam_fallback_seal").raw,u_=P.blobFromString("jam_ticket_seal").raw;var h_;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(h_||(h_={}));const f_=async function(e,t,r,s,i,n){const a=P.blobFromParts(t.map(e=>e.raw)).raw,o=await e.verifySeal(a,r,s.raw,i.raw,n.raw);return o[0]===h_.Error?D.error(null):D.ok(L.fromBlob(o.subarray(1),Pe).asOpaque())},g_=async function(e,t,r,s){const i=s.length+u_.length+1,n=P.blobFromParts(r.map(e=>P.blobFromParts([e.signature.raw,u_,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,a=P.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(a,n,i);return Array.from(P.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===h_.Ok,entropyHash:L.fromBlob(e.raw.subarray(1,33),Pe).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:L.zero(Pe).asOpaque()}));throw e}},p_=async function(e,t){const r=P.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===h_.Error?D.error(null):D.ok(L.fromBlob(s.subarray(1),De).asOpaque())};class b_{runInternal;state;static new(e,t){return new b_(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===vE.parentPort)throw new Error("This method is meant to be run inside a worker thread!");vE.parentPort.once("close",()=>{process.exit(0)}),vE.parentPort.once("message",e=>{this.listenTo(e),vE.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=D.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=D.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class m_{workers;maxWorkers;workerPath;static async initialize(e,t){w(t.maxWorkers>0,"Max workers has to be positive."),w(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 y_(e));return new m_(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 y_(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 y_(e){const{port1:t,port2:r}=new MessageChannel,s=new vE.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new A_(s,r)}class A_{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 I_;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(I_||(I_={}));class v_{data;constructor(e){this.data=e}getTransferList(){return[]}}class w_{params;constructor(e){this.params=e}getTransferList(){return[]}}const S_=b_.new(e=>{const t=e.params,r=t.method;return r===I_.RingCommitment?Promise.resolve(new v_(Ue.ring_commitment(t.keys))):r===I_.BatchVerifyTickets?Promise.resolve(new v_(Ue.batch_verify_tickets(t.keys,t.ticketsData,t.contextLength))):r===I_.VerifySeal?Promise.resolve(new v_(Ue.verify_seal(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void E(r)},null);class E_{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=uE().cpus().length;return new E_(e?S_:await m_.initialize(new URL(a(884),a.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new w_({method:I_.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new w_({method:I_.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new w_({method:I_.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const C_=(e,t)=>W(e.id,t.id);var k_,x_,B_,__,R_,O_,U_,T_,N_;!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"}(k_||(k_={}));class D_{chainSpec;state;bandersnatch;constructor(e,t,r=E_.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=je([r.raw,t]).asOpaque();return this.isEpochChanged(e)?yt.new([i,r,s[0],s[1]],4):yt.new([i,...s],4)}async getValidatorKeys(e,t){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return D.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?zE.create({bandersnatch:L.zero(Te).asOpaque(),ed25519:L.zero(mr).asOpaque(),bls:L.zero(Me).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await p_(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?D.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):D.error(k_.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]),Vr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=ne(0);n<r;n++){const r=de(n),a=je([e.raw,r]).raw,o=fe.fromBlob(a).u32()%i;s.push(t[o].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?YE.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:YE.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return ls.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>cs.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 D.error(k_.DuplicateTicket);if(t.isGreater())return D.error(k_.BadTicketOrder)}return D.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await g_(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 D.error(k_.BadTicketProof);const a=this.verifyTickets(n);if(a.isError)return D.error(a.error);if(this.isEpochChanged(e))return D.ok(n);const o=It.fromSortedArray(C_,this.state.ticketsAccumulator),c=It.fromSortedArray(C_,n),l=It.fromTwoSortedCollections(o,c);return o.length+c.length!==l.length?D.error(k_.DuplicateTicket):D.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 D.error(k_.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return D.error(k_.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return D.error(k_.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot,e.punishSet);if(t.isError)return D.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,a=this.getEntropy(e.slot,e.entropy),o=this.getSlotKeySequence(e.slot,s,a[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,a[2]);if(c.isError)return D.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:a,sealingKeySeries:o,ticketsAccumulator:c.ok},d={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return D.ok(d)}}!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"}(x_||(x_={}));class M_{bandersnatch;constructor(e=E_.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=P.blobFromParts(l_,r.ok.raw),i=await f_(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,P.blobFromNumbers([]));return i.isError?D.error(x_.IncorrectEntropySource):D.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return D.error(x_.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),a=t.sealingKeySeries,o=t.currentEntropy;return a.kind===WE.Tickets?await this.verifySealWithTicket(a.tickets,n,o,r,s,e):await this.verifySealWithKeys(a.keys,i,n,o,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const a=t%e.length,{id:o,attempt:c}=e[a],l=P.blobFromParts(u_,r.raw,new Uint8Array([c])),d=await f_(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,ds(n));return d.isError?D.error(x_.IncorrectSeal):o.isEqualTo(d.ok)?D.ok(d.ok):D.error(x_.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,a){const o=e[r%e.length];if(!o.isEqualTo(t.bandersnatch))return D.error(x_.InvalidValidator,`Expected: ${o}, got: ${t.bandersnatch}`);const c=P.blobFromParts(d_,s.raw),l=await f_(await this.bandersnatch,i.map(e=>e.bandersnatch),n,a.seal.materialize(),c,ds(a));return l.isError?D.error(x_.IncorrectSeal):D.ok(l.ok)}}function P_(e){if(e.length===B_.Requested)return{status:B_.Requested};if(e.length===B_.Available)return{status:B_.Available,data:[e[0]]};if(e.length===B_.Unavailable)return{status:B_.Unavailable,data:[e[0],e[1]]};if(e.length===B_.Reavailable)return{status:B_.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"}(B_||(B_={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(__||(__={})),function(e){e[e.NotFound=0]="NotFound",e[e.NotExpired=1]="NotExpired",e[e.StorageUtilisationError=2]="StorageUtilisationError"}(R_||(R_={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(O_||(O_={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(U_||(U_={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(T_||(T_={})),function(e){e[e.InsufficientFunds=0]="InsufficientFunds",e[e.UnprivilegedService=1]="UnprivilegedService"}(N_||(N_={}));class L_{source;destination;amount;memo;gas;static Codec=Be.Class(L_,{source:Be.u32.asOpaque(),destination:Be.u32.asOpaque(),amount:Be.u64,memo:Be.bytes(128),gas:Be.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 L_(e,t,r,s,i)}}const H_="insufficient funds";class V_{services;transfers;yieldedRoots;authorizationQueues=new Map;validatorsData=null;privilegedServices=null;constructor(e,t,r=new Map){this.services=e,this.transfers=t,this.yieldedRoots=r}static empty(){return new V_({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new V_({...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 V_(t,r,new Map(e.yieldedRoots));for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return null!==e.validatorsData&&(s.validatorsData=[...e.validatorsData]),null!==e.privilegedServices&&(s.privilegedServices=LE.create({...e.privilegedServices,authManager:[...e.privilegedServices.authManager]})),s}}class K_{state;stateUpdate;constructor(e,t){this.state=e,this.stateUpdate=void 0===t?V_.empty():V_.copyFrom(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===aC.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:ne(Number(e))}(s);if(null===i||null===e)return null;const n=e.getLookupHistory(r,i);return null===n?null:new nC(r,i,n)};if(void 0===i)return n();const{action:a}=i;switch(a.kind){case aC.Provide:return new nC(r,i.length,iC([e]));case aC.Remove:{const t=n();return null===t?null:new nC(r,t.length,iC([...t.slots,e]))}case aC.UpdateOrAdd:return a.item}E(a)}updateStorage(e,t,r){const s=null===r?uC.remove({serviceId:e,key:t}):uC.set({serviceId:e,storage:sC.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){w(t>=0,`storageUtilisationCount has to be a positive number, got: ${t}`),w(r>=0,`storageUtilisationBytes has to be a positive number, got: ${r}`);const i=!ae(t),n=!ce(r);if(i||n)return D.error(H_);const a=tC.calculateThresholdBalance(t,r,s.gratisStorage);return s.balance<a?D.error(H_):(this.updateServiceInfo(e,tC.create({...s,storageUtilisationBytes:r,storageUtilisationCount:t})),D.ok(O))}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!==oC.Create?this.stateUpdate.services.servicesUpdates.splice(r,s,dC.update({serviceId:e,serviceInfo:t})):this.stateUpdate.services.servicesUpdates.splice(r,s,dC.create({serviceId:e,serviceInfo:t,lookupHistory:i.action.lookupHistory}))}getPrivilegedServices(){return null!==this.stateUpdate.privilegedServices?this.stateUpdate.privilegedServices:this.state.privilegedServices}}const Q_=oe(81),F_=v.isGreaterOrEqual(h.V0_6_7)?oe(34):oe(32),$_=Zs.new(void 0,"accumulate-externalities");class G_{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:P_(s.slots);if(i?.status!==B_.Unavailable)return[!1,"wrong status"];const n=this.currentTimeslot,a=i.data[1]<n-this.chainSpec.preimageExpungePeriod;return[a,a?"":"not expired"]}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=Nr((t-256+1+r)%r+256)}}getManager(){return this.updatedState.getPrivilegedServices().manager}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:P_(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===B_.Requested)return D.error(__.AlreadyRequested);if(e===B_.Available||e===B_.Reavailable)return D.error(__.AlreadyAvailable);w(e===B_.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,a=t-BigInt(r?.length??0),o=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(a)+(i?0n:Q_),l=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,o,c,s);if(l.isError)return D.error(__.InsufficientFunds,l.details);const d=RB(t);return null===r?this.updatedState.updatePreimage(lC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new nC(e,d,iC([]))})):this.updatedState.updatePreimage(lC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new nC(e,d,iC([...r.slots,this.currentTimeslot]))})),D.ok(O)}forgetPreimage(e,t){const r=this.currentServiceId,s=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null===s)return D.error(R_.NotFound);const i=P_(s.slots),n=()=>{const e=this.getCurrentServiceInfo(),r=e.storageUtilisationCount-2,s=e.storageUtilisationBytes-t-Q_;return this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,r,s,e)};if(i.status===B_.Requested)return n().isError?D.error(R_.StorageUtilisationError):(this.updatedState.updatePreimage(lC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O));const a=this.currentTimeslot;return i.status===B_.Unavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?n().isError?D.error(R_.StorageUtilisationError):(this.updatedState.updatePreimage(lC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O)):D.error(R_.NotExpired):i.status===B_.Available?(this.updatedState.updatePreimage(lC.updateOrAdd({serviceId:r,lookupHistory:new nC(s.hash,s.length,iC([i.data[0],a]))})),D.ok(O)):i.status===B_.Reavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(lC.updateOrAdd({serviceId:r,lookupHistory:new nC(s.hash,s.length,iC([i.data[2],a]))})),D.ok(O)):D.error(R_.NotExpired):void E(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return D.error(O_.DestinationNotFound);if(r<n.onTransferMinGas)return D.error(O_.GasTooLow);const a=i.balance-t;return a<tC.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes,i.gratisStorage)?D.error(O_.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(L_.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,tC.create({...i,balance:oe(a)})),D.ok(O))}newService(e,t,r,s,i){const n=this.nextNewServiceId,a=ne(2),o=le(Q_,t),c=RB(t);if(i!==oe(0)&&this.currentServiceId!==this.getManager())return D.error(N_.UnprivilegedService);const l=tC.calculateThresholdBalance(a,o.value,i),d=this.getCurrentServiceInfo(),u=tC.calculateThresholdBalance(d.storageUtilisationCount,d.storageUtilisationBytes,d.gratisStorage),h=d.balance-l;return h<u||o.overflow?D.error(N_.InsufficientFunds):(this.updatedState.stateUpdate.services.servicesUpdates.push(dC.create({serviceId:n,serviceInfo:tC.create({codeHash:e,balance:l,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:a,gratisStorage:i,created:this.currentTimeslot,lastAccumulation:Ur(0),parentService:this.currentServiceId}),lookupHistory:new nC(e.asOpaque(),c,iC([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,tC.create({...d,balance:oe(h)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return Nr(256+(e-256+42+t)%t)}(n)),D.ok(n))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updateServiceInfo(this.currentServiceId,tC.create({...s,codeHash:e,accumulateMinGas:Dr(t),onTransferMinGas:Dr(r)}))}updateValidatorsData(e){const t=this.updatedState.getPrivilegedServices().validatorsManager;t===this.currentServiceId?this.updatedState.stateUpdate.validatorsData=e:$_.trace(`Current service id (${this.currentServiceId}) is not a validator manager (${t}) and cannot update validators. Ignoring.`)}checkpoint(){this.checkpointedState=V_.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t){const r=this.updatedState.getPrivilegedServices().authManager[e];r===this.currentServiceId?this.updatedState.stateUpdate.authorizationQueues.set(e,t):$_.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=LE.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>PE.create({service:e,gasLimit:t}))}):$_.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 D.error(T_.ServiceNotFound);const r=qe(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,oe(t.length));return null!==s&&nC.isRequested(s)?this.updatedState.hasPreimage(e,r)?D.error(T_.AlreadyProvided):(this.updatedState.updatePreimage(lC.provide({serviceId:e,preimage:rC.create({hash:r,blob:t}),slot:this.currentTimeslot})),D.ok(O)):D.error(T_.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return D.error(U_.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=L.zero(Pe).asOpaque();if(function(e,t){w(t.length>=4,"Not enough space in the destination."),t.set(de(e))}(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return D.error(U_.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return D.error(U_.InvalidPreimage,"Too many storage items");const n=oe(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,Q_)-Q_),[a,o]=this.isPreviousCodeExpired(e,t,n);if(!a)return D.error(U_.InvalidPreimage,`Previous code available: ${o}`);const c=le(s.balance,r.balance);return c.overflow?D.error(U_.InvalidService,"Balance overflow"):(this.updatedState.updateServiceInfo(this.currentServiceId,tC.create({...s,balance:c.value})),this.updatedState.stateUpdate.services.servicesRemoved.push(e),D.ok(O))}read(e,t){return null===e?null:this.updatedState.getStorage(e,t)}write(e,t){const r=oe(e.length),s=this.read(this.currentServiceId,e),i=null===s&&null!==t,n=null!==s&&null===t,a=i?1:n?-1:0,o=(t?.length??0)-(s?.length??0),c=i?F_:n?-F_:0n,l=v.isGreaterOrEqual(h.V0_6_7)?i?r:n?-r:0n:0n,d=this.getCurrentServiceInfo(),u=d.storageUtilisationCount+a,f=d.storageUtilisationBytes+BigInt(o)+c+l,g=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,u,f,d);return g.isError?D.error("full",g.details):(this.updatedState.updateStorage(this.currentServiceId,e,t),D.ok(null===s?null:s.length))}lookup(e,t){return null===e?null:this.updatedState.getPreimage(e,t)}}class j_ extends B{static Codec=Be.Class(j_,v.isSuite(f.JAMDUNA,h.V0_6_5)?{hash:Be.bytes(Pe).asOpaque(),exportsRoot:Be.bytes(Pe).asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),authorizationOutput:Be.blob,payloadHash:Be.bytes(Pe),gas:Be.varU64.asOpaque(),result:Xr.Codec}:{hash:Be.bytes(Pe).asOpaque(),exportsRoot:Be.bytes(Pe).asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),payloadHash:Be.bytes(Pe),gas:Be.varU64.asOpaque(),result:Xr.Codec,authorizationOutput:Be.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:a}){return new j_({gas:Dr(s),payloadHash:n.asOpaque(),result:a,authorizationOutput:P.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 j_(e)}}class q_{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new q_([],ne(0),Dr(0n))}}class z_{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)??q_.empty();n.reportsLength=ne(n.reportsLength+1),n.gasCost=Dr(n.gasCost+e.gas),n.operands.push(j_.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=Dr(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??ne(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??Dr(0n)}getServiceIds(){return this.serviceIds}}function W_(e){const t=e.map(e=>e.workPackageSpec.hash);return bt.from(t)}const J_=Be.object({serviceId:Be.u32.asOpaque(),entropy:Be.bytes(Pe).asOpaque(),timeslot:Be.u32.asOpaque()});class Y_{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(bt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return X_(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>EC.create({report:e,dependencies:this.getWorkReportDependencies(e)})),bt.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=X_(r,W_(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 X_(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return EC.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}const Z_=Be.object({serviceId:Be.u32.convert(e=>e,e=>e),gas:Be.u64.convert(e=>oe(e),e=>Dr(e))});class eR{currentServiceId;index=Uk(0);gasCost=Gk(10);tracedRegisters=Dk(7);constructor(e){this.currentServiceId=e}execute(e,t){const r=v.isSuite(f.JAMDUNA,h.V0_6_5)?BigInt(e.get())-10n:e.get();return t.set(7,oe(r)),Promise.resolve(void 0)}}const tR=be(zE.Codec.sizeHint),rR=e=>oe(e);var sR,iR,nR,aR,oR;!function(e){e[e.Void=0]="Void",e[e.ZeroRead=1]="ZeroRead",e[e.ZeroWrite=2]="ZeroWrite",e[e.Read=3]="Read",e[e.Write=4]="Write"}(sR||(sR={})),function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(iR||(iR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(nR||(nR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidOperation=1]="InvalidOperation",e[e.InvalidPage=2]="InvalidPage"}(aR||(aR={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class cR{currentServiceId;fetch;index=Uk(v.selectIfGreaterOrEqual({fallback:18,versions:{[h.V0_6_7]:1}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=oe(s?.length??0),a=he(t.get(8),n),o=he(t.get(9),oe(n-a)),c=null===s?new Uint8Array:s.raw.subarray(Number(a),Number(a+o));if(r.storeFrom(i,c).isError)return Tk.Panic;t.set(7,null===s?EB.NONE:n)}getValue(e){const t=RB(e.get(10));if(t===oR.Constants)return this.fetch.constants();if(t===oR.Entropy)return this.fetch.entropy();if(t===oR.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===oR.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===oR.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===oR.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===oR.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===oR.WorkPackage)return this.fetch.workPackage();if(t===oR.Authorizer)return this.fetch.authorizer();if(t===oR.AuthorizationToken)return this.fetch.authorizationToken();if(t===oR.RefineContext)return this.fetch.refineContext();if(t===oR.AllWorkItems)return this.fetch.allWorkItems();if(t===oR.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===oR.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===oR.AllOperands)return this.fetch.allOperands();if(t===oR.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===oR.AllTransfers)return this.fetch.allTransfers();if(t===oR.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"}(oR||(oR={}));class lR{currentServiceId;account;index=Uk(v.selectIfGreaterOrEqual({fallback:4,versions:{[h.V0_6_7]:5}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=BB(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),a=null===n?P.empty():Ae.encodeObject(dR,{...n,thresholdBalance:tC.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes,n.gratisStorage)});if(r.storeFrom(i,a.raw).isError)return Tk.Panic;null!==n?t.set(7,EB.OK):t.set(7,EB.NONE)}}const dR=v.isGreaterOrEqual(h.V0_6_7)?Be.object({codeHash:Be.bytes(Pe),balance:Be.u64,thresholdBalance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,storageUtilisationCount:Be.u32,gratisStorage:Be.u64,created:Be.u32.convert(e=>e,Ur),lastAccumulation:Be.u32.convert(e=>e,Ur),parentService:Be.u32.convert(e=>e,Nr)},"ServiceAccountInfoWithThresholdBalance"):Be.object({codeHash:Be.bytes(Pe),balance:Be.varU64,thresholdBalance:Be.varU64,accumulateMinGas:Be.varU64.convert(e=>e,Dr),onTransferMinGas:Be.varU64.convert(e=>e,Dr),storageUtilisationBytes:Be.varU64,storageUtilisationCount:Be.varU32,gratisStorage:eC(oe(0)),created:eC(Ur(0)),lastAccumulation:eC(Ur(0)),parentService:eC(Nr(0))},"ServiceAccountInfoWithThresholdBalance"),uR=Zs.new(void 0,"host-calls"),hR=new TextDecoder("utf8");class fR{currentServiceId;index=Uk(100);gasCost=Gk(0);tracedRegisters=Dk();constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),a=t.get(10),o=t.get(11),c=new Uint8Array(RB(n)),l=new Uint8Array(RB(o));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,a),uR.trace(`[${this.currentServiceId}] [${s}] ${hR.decode(c)} ${hR.decode(l)}`),Promise.resolve(void 0)}}class gR{currentServiceId;account;index=Uk(v.selectIfGreaterOrEqual({fallback:1,versions:{[h.V0_6_7]:2}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=BB(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=L.zero(Pe);if(r.loadInto(a.raw,i).isError)return Tk.Panic;const o=this.account.lookup(s,a),c=oe(null===o?0:o.raw.length),l=t.get(10),d=t.get(11),u=he(l,c),h=he(d,oe(c-u)),f=null===o?new Uint8Array(0):o.raw.subarray(Number(u),Number(u+h));if(r.storeFrom(n,f).isError)return Tk.Panic;null!==o?t.set(7,c):t.set(7,EB.NONE)}}class pR{currentServiceId;account;index=Uk(v.selectIfGreaterOrEqual({fallback:2,versions:{[h.V0_6_7]:3}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=BB(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=t.get(10),o=RB(n),c=new Uint8Array(o);if(r.loadInto(c,i).isError)return Tk.Panic;const l=this.account.read(s,P.blobFrom(c)),d=oe(null===l?0:l.raw.length),u=t.get(11),h=t.get(12),f=he(u,d),g=he(h,oe(d-f)),p=null===l?new Uint8Array(0):l.raw.subarray(Number(f),Number(f+g));if(r.storeFrom(a,p).isError)return Tk.Panic;null!==l?t.set(7,d):t.set(7,EB.NONE)}}class bR{currentServiceId;account;index=Uk(v.selectIfGreaterOrEqual({fallback:3,versions:{[h.V0_6_7]:4}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,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),a=t.get(10),o=RB(i),c=new Uint8Array(o);if(r.loadInto(c,s).isError)return Tk.Panic;const l=P.blobFrom(c),d=RB(a),u=new Uint8Array(d);if(r.loadInto(u,n).isError)return Tk.Panic;const h=0n===a?null:P.blobFrom(u),f=this.account.write(l,h);f.isError?t.set(7,EB.FULL):t.set(7,null===f.ok?EB.NONE:oe(f.ok))}}const mR=[class{currentServiceId;partialState;chainSpec;index=Uk(v.selectIfGreaterOrEqual({fallback:5,versions:{[h.V0_6_7]:14}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,10,11);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=_B(t.get(7)),i=_B(t.get(8)),n=_B(t.get(9)),a=t.get(10),o=t.get(11),c=new Array,l=new Uint8Array(be(Z_.sizeHint)),d=fe.fromBlob(l);let u=a;for(let e=0n;e<o;e+=1n){if(d.resetTo(0),r.loadInto(l,u).isError)return Tk.Panic;const{serviceId:e,gas:t}=d.object(Z_);c.push([e,t]),u=oe(u+oe(d.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,OE(new Array(this.chainSpec.coresCount).fill(i),this.chainSpec),n,c),t.set(7,EB.OK)):t.set(7,EB.WHO)}},class{currentServiceId;partialState;chainSpec;index=Uk(v.selectIfGreaterOrEqual({fallback:6,versions:{[h.V0_6_7]:15}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);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 Tk.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,EB.CORE);const a=fe.fromBlob(n).sequenceFixLen(Be.bytes(Pe),80),o=yt.new(a,80);t.set(7,EB.OK),this.partialState.updateAuthorizationQueue(Mr(Number(s)),o)}},class{currentServiceId;partialState;chainSpec;index=Uk(v.selectIfGreaterOrEqual({fallback:7,versions:{[h.V0_6_7]:16}}));gasCost=Gk(10);tracedRegisters=Dk(7);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(tR*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return Tk.Panic;const n=fe.fromBlob(i).sequenceFixLen(zE.Codec,this.chainSpec.validatorsCount);t.set(7,EB.OK),this.partialState.updateValidatorsData(Lr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:8,versions:{[h.V0_6_7]:17}}));gasCost=Gk(10);tracedRegisters;gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new eR(e),this.tracedRegisters=this.gasHostCall.tracedRegisters}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:9,versions:{[h.V0_6_7]:18}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Dr(t.get(9)),a=Dr(t.get(10)),o=v.isGreaterOrEqual(h.V0_6_7)?t.get(11):oe(0),c=L.zero(Pe);if(r.loadInto(c.raw,s).isError)return Tk.Panic;const l=this.partialState.newService(c.asOpaque(),i,n,a,o);if(l.isOk)return void t.set(7,oe(l.ok));const d=l.error;d!==N_.InsufficientFunds?d!==N_.UnprivilegedService?E(d):t.set(7,EB.HUH):t.set(7,EB.CASH)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:10,versions:{[h.V0_6_7]:19}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9);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),a=L.zero(Pe);if(r.loadInto(a.raw,s).isError)return Tk.Panic;this.partialState.upgradeService(a.asOpaque(),i,n),t.set(7,EB.OK)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:11,versions:{[h.V0_6_7]:20}}));gasCost=e=>{const t=10n+e.get(9);return qk(t)};tracedRegisters=Dk(7,8,9,10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=_B(t.get(7)),i=t.get(8),n=Dr(t.get(9)),a=t.get(10),o=L.zero(128);if(r.loadInto(o.raw,a).isError)return Tk.Panic;const c=this.partialState.transfer(s,i,n,o);if(c.isOk)return void t.set(7,EB.OK);const l=c.error;l!==O_.DestinationNotFound?l!==O_.GasTooLow?l!==O_.BalanceBelowThreshold?E(l):t.set(7,EB.CASH):t.set(7,EB.LOW):t.set(7,EB.WHO)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:12,versions:{[h.V0_6_7]:21}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=_B(t.get(7)),i=t.get(8),n=L.zero(Pe).asOpaque();if(r.loadInto(n.raw,i).isError)return Tk.Panic;if(s===this.currentServiceId)return void t.set(7,EB.WHO);const a=this.partialState.eject(s,n);if(a.isOk)return void t.set(7,EB.OK);const o=a.error;o===U_.InvalidService?t.set(7,EB.WHO):o===U_.InvalidPreimage?t.set(7,EB.HUH):E(o)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:13,versions:{[h.V0_6_7]:22}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Tk.Panic;const a=this.partialState.checkPreimageStatus(n.asOpaque(),i),o=oe(0n);if(null===a)return t.set(7,EB.NONE),void t.set(8,o);switch(a.status){case B_.Requested:return t.set(7,o),void t.set(8,o);case B_.Available:return t.set(7,oe(1n+(BigInt(a.data[0])<<32n))),void t.set(8,o);case B_.Unavailable:return t.set(7,oe(2n+(BigInt(a.data[0])<<32n))),void t.set(8,oe(a.data[1]));case B_.Reavailable:return t.set(7,oe(3n+(BigInt(a.data[0])<<32n))),void t.set(8,oe((BigInt(a.data[2])<<32n)+BigInt(a.data[1])))}}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:14,versions:{[h.V0_6_7]:23}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Tk.Panic;const a=this.partialState.requestPreimage(n.asOpaque(),i);if(a.isOk)return void t.set(7,EB.OK);const o=a.error;o!==__.AlreadyAvailable&&o!==__.AlreadyRequested?o!==__.InsufficientFunds?E(o):t.set(7,EB.FULL):t.set(7,EB.HUH)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:15,versions:{[h.V0_6_7]:24}}));gasCost=Gk(10);tracedRegisters=Dk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Tk.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,EB.OK):t.set(7,EB.HUH)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:16,versions:{[h.V0_6_7]:25}}));gasCost=Gk(10);tracedRegisters=Dk(7);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=L.zero(Pe);if(r.loadInto(i.raw,s).isError)return Tk.Panic;this.partialState.yield(i),t.set(7,EB.OK)}},class{currentServiceId;partialState;index=Uk(v.selectIfGreaterOrEqual({fallback:27,versions:{[h.V0_6_7]:26}}));gasCost=Gk(10);tracedRegisters=Dk(7,8,9);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=BB(7,t,this.currentServiceId),i=t.get(8),n=RB(t.get(9)),a=P.blobFrom(new Uint8Array(n));if(r.loadInto(a.raw,i).isError)return Tk.Panic;const o=this.partialState.providePreimage(s,a);if(o.isOk)return void t.set(7,EB.OK);const c=o.error;c!==T_.ServiceNotFound?c!==T_.WasNotRequested&&c!==T_.AlreadyProvided?E(c):t.set(7,EB.HUH):t.set(7,EB.WHO)}}];var yR,AR;!function(e){e.IS_AUTHORIZED=rR(0),e.REFINE=rR(0),e.ACCUMULATE=rR(5),e.ON_TRANSFER=rR(10)}(yR||(yR={}));class IR{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new SB(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new UB(...t),this.pvm=new wB(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=mR.map(s=>new s(e,t.partialState,r)),i=[new fR(e),new eR(e),new pR(e,t.serviceExternalities),new bR(e,t.serviceExternalities),new cR(e,t.fetchExternalities),new gR(e,t.serviceExternalities),new lR(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new fR(e),new eR(e),new cR(e,t.fetchExternalities),new pR(e,t.partialState),new bR(e,t.partialState),new gR(e,t.partialState),new lR(e,t.partialState)]}async run(e,t){const r=$B.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=IR.prepareAccumulateHostCalls(e,r,s);return new IR(t,i,yR.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=IR.prepareOnTransferHostCalls(e,r);return new IR(t,s,yR.ON_TRANSFER)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(AR||(AR={}));const vR=10000000n,wR=Zs.new(void 0,"accumulate"),SR=Be.object({slot:Be.u32.asOpaque(),serviceId:Be.u32.asOpaque(),operands:Be.sequenceVarLen(j_.Codec)}),ER=Be.object({slot:Be.varU32.asOpaque(),serviceId:Be.varU32.asOpaque(),operands:Be.varU32});class CR{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 a=this.state.getService(t);if(null===a)return wR.log(`Service with id ${t} not found.`),D.error(AR.NoService);const o=a.getInfo().codeHash,c=a.getPreimage(o.asOpaque());if(null===c)return wR.log(`Code with hash ${o} not found for service ${t}.`),D.error(AR.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=ue(qe(Ae.encodeObject(J_,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return Nr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),d=new G_(this.chainSpec,new K_(this.state,n),t,l,e),u={partialState:d,serviceExternalities:d,fetchExternalities:NR.createForAccumulate({entropy:i,operands:r},this.chainSpec)},f=IR.createAccumulateExecutor(t,c,u,this.chainSpec);let g=P.empty();g=v.is(h.V0_6_5)?Ae.encodeObject(SR,{slot:e,serviceId:t,operands:r},this.chainSpec):Ae.encodeObject(ER,{slot:e,serviceId:t,operands:ne(r.length)});const p=await f.run(g,qk(s)),[b,m]=d.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===xk.OOG||e===xk.PANIC)return D.ok({stateUpdate:m,consumedGas:Dr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Pe){const e=L.fromBlob(p.memorySlice,Pe);b.yieldedRoots.set(t,e.asOpaque())}return D.ok({stateUpdate:b,consumedGas:Dr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){wR.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const a=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return a.isError?(wR.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(wR.trace(`Accumulation successful for ${e}. Consumed: ${a.ok.consumedGas}`),a.ok)}async accumulateSequentially(e,t,r,s,i,n){const a=this.findReportCutoffIndex(e,t);if(0===a)return{accumulatedReports:ne(0),gasCost:Dr(0),state:n};const o=t.slice(0,a),c=this.state.privilegedServices.autoAccumulateServices,l=new z_(o,c),d=t.slice(a),{gasCost:u,state:h,...f}=await this.accumulateInParallel(l,r,s,i,n);C(f);const{accumulatedReports:g,gasCost:p,state:b,...m}=await this.accumulateSequentially(Dr(e-u),d,r,s,i,h);return C(m),{accumulatedReports:ne(a+g),gasCost:Dr(u+p),state:b}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds();let a=Dr(0),o=i;for(const i of n){const n=V_.copyFrom(o),{consumedGas:c,stateUpdate:l}=await this.accumulateSingleService(i,e.getOperands(i),e.getGasCost(i),t,r,o);a=Dr(a+c);const d=s.get(i)??{count:ne(0),gasUsed:Dr(0)};d.count=ne(d.count+e.getReportsLength(i)),d.gasUsed=Dr(d.gasUsed+c),s.set(i,d),o=null===l?n:l}return{state:o,gasCost:a}}getAccumulationStateUpdate(e,t,r,s,i){const n=this.chainSpec.epochLength,a=r%n,o=W_(e),c=Array.from(o).sort((e,t)=>ME(e,t).value),l=Vr(this.state.recentlyAccumulated.slice(1).concat(bt.from(c)),this.chainSpec),d=this.state.accumulationQueue.slice();d[a]=X_(t,o);for(let e=1;e<n;e++){const t=(a+n-e)%n;e<r-this.state.timeslot?d[t]=[]:d[t]=X_(d[t],o)}const u=new K_(this.state,V_.new(i));if(v.isGreaterOrEqual(h.V0_6_7))for(const e of s){const t=u.getServiceInfo(e);null!==t&&u.updateServiceInfo(e,tC.create({...t,lastAccumulation:r}))}return{recentlyAccumulated:l,accumulationQueue:Vr(d,this.chainSpec),timeslot:r,...u.stateUpdate.services}}getGasLimit(){const e=vR*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Dr(this.chainSpec.maxBlockGas>e?this.chainSpec.maxBlockGas:e);return Dr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new Y_(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),a=i.getWorkReportsToAccumulateLater(e),o=X_(i.getQueueFromState(t).concat(a),W_(n)),c=i.enqueueReports(o),l=n.concat(c),d=this.getGasLimit(),{accumulatedReports:u,gasCost:h,state:f,...g}=await this.accumulateSequentially(d,l,t,r,s,V_.empty());C(g);const p=l.slice(0,u),{services:b,yieldedRoots:m,transfers:y,validatorsData:A,privilegedServices:I,authorizationQueues:v,...w}=f;C(w);const S=this.getAccumulationStateUpdate(p,a,t,Array.from(s.keys()),b),E=await async function(e){const t=await ft.create(),r=(s=t,{hashConcat:(e,t=[])=>gt(s,[e,...t].map(P.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 L.zero(Pe).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(P.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>P.blobFromParts([de(e),t.raw])),r)}(Array.from(m.entries())),k=(()=>{if(0===v.size)return{};const e=this.state.authQueues.slice();for(const[t,r]of v.entries())e[t]=r;return{authQueues:OE(e,this.chainSpec)}})();return D.ok({root:E,stateUpdate:{...S,...null===A?{}:{designatedValidatorData:A},...null===I?{}:{privilegedServices:I},...k},accumulationStatistics:s,pendingTransfers:y})}}var kR;!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"}(kR||(kR={}));class xR{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=yt.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:a,bitfield:o}=r;if(!s.isEqualTo(e.parentHash))return D.error(kR.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=a)return D.error(kR.InvalidOrder,`order: expected: ${n+1}, got: ${a}`);n=r.validatorIndex,w(o.bitLength===t,`Invalid bitfield length of ${o.bitLength}`);const c=o.indicesOfSetBits();for(const e of c)i[e]+=1}const a=[],o=[],c=this.chainSpec.validatorsSuperMajority,l=e.disputesAvailAssignment.slice();for(let r=0;r<t;r++){const t=i[r],s=l[r],n=null!==s;if(t>0&&!n)return D.error(kR.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&o.push(r),t>=c&&(a.push(s.workReport.data),o.push(r)))}const d=await r;if(d.isError)return d;for(const e of o)l[e]=null;return D.ok({availableReports:a,stateUpdate:{availabilityAssignment:l}})}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 D.error(kR.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:_R(e.anchor.encoded(),e.bitfield.encoded())})}const s=await wr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return D.error(kR.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return D.ok(O)}}const BR=P.blobFromString("jam_available").raw;function _R(e,t){return P.blobFromParts(BR,qe(P.blobFromParts(e.raw,t.raw)).raw)}var RR;!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",e[e.BannedValidator=23]="BannedValidator"}(RR||(RR={}));const OR=Be.object({B_I:Be.u64,B_L:Be.u64,B_S:Be.u64,C:Be.u16,D:Be.u32,E:Be.u32,G_A:Be.u64,G_I:Be.u64,G_R:Be.u64,G_T:Be.u64,H:Be.u16,I:Be.u16,J:Be.u16,K:Be.u16,L:Be.u32,N:Be.u16,O:Be.u16,P:Be.u16,Q:Be.u16,R:Be.u16,T:Be.u16,U:Be.u16,V:Be.u16,W_A:Be.u32,W_B:Be.u32,W_C:Be.u32,W_E:Be.u32,W_M:Be.u32,W_P:Be.u32,W_R:Be.u32,W_T:Be.u32,W_X:Be.u32,Y:Be.u32}),UR=new Map;var TR;!function(e){e[e.Accumulate=0]="Accumulate",e[e.OnTransfer=1]="OnTransfer"}(TR||(TR={}));class NR{fetchData;chainSpec;constructor(e,t){this.fetchData=e,this.chainSpec=t}static createForAccumulate(e,t){return new NR({context:TR.Accumulate,...e},t)}static createForOnTransfer(e,t){return new NR({context:TR.OnTransfer,...e},t)}constants(){return function(e){const t=UR.get(e);if(void 0!==t)return t;const r=Ae.encodeObject(OR,{B_I:oe(10n),B_L:oe(1n),B_S:oe(100n),C:se(e.coresCount),D:ne(e.preimageExpungePeriod),E:ne(e.epochLength),G_A:oe(vR),G_I:oe(5e7),G_R:oe(e.maxRefineGas),G_T:oe(e.maxBlockGas),H:se(8),I:se(zr),J:se(8),K:se(16),L:ne(14400),N:se(2),O:se(8),P:se(e.slotDuration),Q:se(80),R:se(e.rotationPeriod),T:se(128),U:se(5),V:e.validatorsCount,W_A:ne(64e3),W_B:ne(13794305),W_C:ne(4e6),W_E:ne(e.erasureCodedPieceSize),W_M:ne(3072),W_P:ne(e.numberECPiecesPerSegment),W_R:ne(49152),W_T:ne(128),W_X:ne(3072),Y:ne(e.contestLength)});return UR.set(e,r),r}(this.chainSpec)}entropy(){const{entropy:e}=this.fetchData;return void 0===e?null:e.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(){if(this.fetchData.context!==TR.Accumulate)return null;const e=this.fetchData.operands;return Ae.encodeObject(Be.sequenceVarLen(j_.Codec),e,this.chainSpec)}oneOperand(e){if(this.fetchData.context!==TR.Accumulate)return null;const{operands:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ae.encodeObject(j_.Codec,r,this.chainSpec)}allTransfers(){if(this.fetchData.context!==TR.OnTransfer)return null;const{transfers:e}=this.fetchData;return Ae.encodeObject(Be.sequenceVarLen(L_.Codec),e,this.chainSpec)}oneTransfer(e){if(this.fetchData.context!==TR.OnTransfer)return null;const{transfers:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ae.encodeObject(L_.Codec,r,this.chainSpec)}}const DR=Be.object({timeslot:Be.u32.asOpaque(),serviceId:Be.u32.asOpaque(),transfers:Be.sequenceVarLen(L_.Codec)}),MR=Be.object({timeslot:Be.varU32.asOpaque(),serviceId:Be.varU32.asOpaque(),transfersLength:Be.varU32});var PR;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(PR||(PR={}));const LR=Zs.new(void 0,"deferred-transfers");class HR{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition({pendingTransfers:e,timeslot:t,servicesUpdate:r,entropy:s}){const i=new Map,n=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]));let a=V_.new(r);for(const r of n){const n=new K_(this.state,a),o=e.filter(e=>e.destination===r),c=n.getServiceInfo(r);if(null===c)return D.error(PR.ServiceInfoNotExist);const l=c.codeHash,d=n.getPreimage(r,l.asOpaque()),u=le(c.balance,...o.map(e=>e.amount));if(u.overflow)return D.error(PR.ServiceBalanceOverflow);const f=tC.create({...c,balance:u.value});n.updateServiceInfo(r,f);const g=new G_(this.chainSpec,n,r,r,t),p=NR.createForOnTransfer({entropy:s,transfers:o},this.chainSpec);let b=qk(0);if(null===d||0===o.length)LR.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`);else{const e=()=>v.isGreaterOrEqual(h.V0_6_7)?Ae.encodeObject(MR,{timeslot:t,serviceId:r,transfersLength:ne(o.length)},this.chainSpec):Ae.encodeObject(DR,{timeslot:t,serviceId:r,transfers:o},this.chainSpec),s=IR.createOnTransferExecutor(r,d,{partialState:g,fetchExternalities:p}),i=e(),n=o.reduce((e,t)=>e+t.gas,0n);b=(await s.run(i,qk(n))).consumedGas}i.set(r,{count:ne(o.length),gasUsed:Dr(b)});const[m,y]=g.getStateUpdates();a=m,w(null===y,"On transfer cannot invoke checkpoint.")}return D.ok({servicesUpdate:a.services,transferStatistics:i})}}class VR{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]=mt(s)}return{authPools:OE(t,this.chainSpec)}}}class KR{hasher;state;constructor(e,t){this.hasher=e,this.state=t}partialTransition(e){const t=this.state.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null;return null!==r&&(r.postStateRoot=e.priorStateRoot),{recentBlocks:this.state.recentBlocks.updateBlocks(t)}}transition(e){const t=e.partial.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null,s=v.isGreaterOrEqual(h.V0_6_7)?null!==this.state.recentBlocks.asCurrent().accumulationLog?VE.fromPeaks(this.hasher,this.state.recentBlocks.asCurrent().accumulationLog):VE.empty(this.hasher):null!==r?VE.fromPeaks(this.hasher,r.mmr):VE.empty(this.hasher);s.append(e.accumulateRoot);const i=s.getPeaks();return v.isGreaterOrEqual(h.V0_6_7)?t.push($E.create({headerHash:e.headerHash,accumulationResult:s.getSuperPeakHash(),postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})):t.push(QE.create({headerHash:e.headerHash,mmr:i,postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})),t.length>8&&t.shift(),{recentBlocks:v.isGreaterOrEqual(h.V0_6_7)?jE.create(GE.create({blocks:t,accumulationLog:i})):jE.legacyCreate(FE.create({blocks:t}))}}}function QR(e,t,r){return function(e,t,r){const s=FR(Ur(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){w(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(de(ne(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=ue(qe(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),a=s,o=r.coresCount,n.map(e=>(e+a)%o));var n,a,o;return i}(t,r,e)}function FR(e,t){return Math.floor(e/t)}const $R=P.blobFromString("jam_guarantee").raw;function GR(e){return P.blobFromParts($R,e.raw)}const jR=1e7;class qR{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 D.error(RR.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return D.error(RR.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return D.ok(O)}(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 D.error(RR.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 D.error(RR.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return D.ok(O)}(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=wr(i.ok),a=this.verifyPostSignatureChecks(e.guarantees,e.assurancesAvailAssignment);if(a.isError)return a;const o=this.verifyContextualValidity(e);if(o.isError)return o;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const d=e.assurancesAvailAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];d[r.coreIndex]=RE.create({workReport:new He(i,r),timeout:e.slot}),l+=1}const u=It.fromArray(W,i.ok.map(e=>e.key)).slice();return function(e,t){for(const r of e)if(t.has(r))return!0;return!1}(u,e.offenders)?D.error(RR.BannedValidator):D.ok({stateUpdate:{availabilityAssignment:OE(d,this.chainSpec)},reported:o.ok,reporters:u})}workReportHashes(e){const t=[];for(const r of e)t.push(_(qe(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let a=0;for(const r of e){const e=r.view(),o=e.report.view().coreIndex.materialize(),c=t[a];a+=1;const l=e.credentials.view();if(l.length<is[0]||l.length>is[1])return D.error(RR.InsufficientGuarantees,`Invalid number of credentials. Expected ${is}, got ${l.length}`);const d=s(n,e.slot.materialize());if(d.isError)return d;const u=d.ok;let h=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(h>=r)return D.error(RR.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${h+1}`);h=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return D.error(RR.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==o)return D.error(RR.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${o}`);i.push({signature:s,key:n.ed25519,message:GR(c)})}}return D.ok(i)}(e.guarantees,t,e.slot,(t,r)=>this.getGuarantorAssignment(t,r,e.newEntropy))}verifyPostSignatureChecks(e,t){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return D.error(RR.CoreEngaged,`Report pending availability at core: ${n}`);const a=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(a)))return D.error(RR.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${a}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return D.error(RR.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return D.error(RR.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const o=le(...e.results.map(e=>e.gas));if(o.overflow||o.value>jR)return D.error(RR.WorkReportGasTooHigh,`Total gas too high. Got: ${o.value} (ovfl: ${o.overflow}), maximal: ${jR}`)}return D.ok(O)}(e,t,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=pt.new(),a=bt.new(),o=bt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=rs.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),a.insertAll(e.report.context.prerequisites),o.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 D.error(RR.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return D.error(RR.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return D.error(RR.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=pt.new();for(const e of r.blocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return D.error(RR.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return D.error(RR.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const a=jE.accumulationResult(t,{hasher:s});if(!a.isEqualTo(r.beefyRoot))return D.error(RR.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${a}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return D.error(RR.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return D.error(RR.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return D.ok(O)}(Math.max(0,e.slot-14400),i,e.recentBlocksPartialUpdate,r,s);if(c.isError)return c;const l=function(e,t){const r=bt.new();for(const e of t.recentBlocks.blocks)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 D.error(RR.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return D.ok(O)}(bt.viewDictionaryKeys(n),t);if(l.isError)return l;const d=pt.new();for(const e of t.recentBlocks.blocks)for(const t of e.reported.values())d.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 D.error(s?RR.SegmentRootLookupInvalid:RR.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return D.ok(O)},n=i(r);if(n.isError)return n;const a=i(s,!0);return a.isError?a:D.ok(O)}({currentWorkPackages:n,recentlyReported:d,prerequisiteHashes:a,segmentRootLookupHashes:o});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=d.get(t.workPackageHash);e=void 0!==r?rs.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return D.error(RR.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return D.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return D.ok(O);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return D.error(RR.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=FR(e,i),a=FR(t,i),o=Math.max(0,n-1)*i;if(t>e)return D.error(RR.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return D.error(RR.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,d=e;n>a&&(d=Ur(e-i),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(d,e,s)&&(c=r[3],l=this.state.previousValidatorData));const u=QR(this.chainSpec,c,d);return D.ok((h=l,f=(e,t)=>({core:e,ed25519:t.ed25519}),u.map((e,t)=>f(e,h[t]))));var h,f}}class zR{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=Lr(Array.from({length:this.chainSpec.validatorsCount},()=>fC.empty()),this.chainSpec);return yC.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return ne(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),ne(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:Dr(t.gasUsed),exported:se(t.exported),imported:se(t.imported),extrinsicCount:se(t.extrinsicCount),extrinsicSize:ne(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:se(t.count),size:ne(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,a=this.getStatistics(t),{current:o,cores:c,services:l}=a;w(void 0!==o[r],"authorIndex is out of bounds");const d=o[r].blocks+1;o[r].blocks=ne(d);const u=o[r].tickets+s.tickets.length;o[r].tickets=ne(u);const h=o[r].preImages+s.preimages.length;o[r].preImages=ne(h);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),g=o[r].preImagesSize+f;o[r].preImagesSize=ne(g);const p=new Set;for(const e of s.guarantees)for(const{validatorIndex:t}of e.credentials)if(!p.has(t)){const e=o[t].guarantees+1;o[t].guarantees=ne(e),p.add(t)}for(const{validatorIndex:e}of s.assurances){const t=o[e].assurances+1;o[e].assurances=ne(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Mr(e),r=i.find(e=>e.coreIndex===t),{imported:a,extrinsicCount:o,extrinsicSize:l,exported:d,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:se(0),extrinsicCount:se(0),extrinsicSize:ne(0),exported:se(0),gasUsed:Dr(0n)},h=n.find(e=>e.coreIndex===t),f=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=a,c[t].extrinsicCount=o,c[t].extrinsicSize=l,c[t].exports=d,c[t].gasUsed=u,c[t].bundleSize=ne(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(h),c[t].popularity=se(f)}l.clear();const b=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of b){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:a,extrinsicCount:o,extrinsicSize:c,exported:d}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:h,size:f}=this.calculateProvidedScoreService(u),{count:g,gasUsed:p}=e.accumulationStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},{count:b,gasUsed:m}=e.transferStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},y=mC.empty();y.refinementCount=ne(r.length),y.refinementGasUsed=n,y.imports=a,y.extrinsicCount=o,y.extrinsicSize=c,y.exports=d,y.providedCount=h,y.providedSize=f,y.providedCount=h,y.providedSize=f,y.accumulateCount=g,y.accumulateGasUsed=p,y.onTransfersCount=b,y.onTransfersGasUsed=m,l.set(t,y)}return{statistics:a}}}class WR{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}const JR="offenders not matching header";var YR;!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",e[e.Offenders=8]="Offenders"}(YR||(YR={}));const XR=(e,t)=>D.taggedError(YR,e,t),ZR=Zs.new(void 0,"stf");class eO{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=E_.new({synchronous:!i});this.statistics=new zR(e,t),this.safrole=new D_(e,t,n),this.safroleSeal=new M_(n),this.recentHistory=new KR(s,t),this.disputes=new c_(e,t),this.reports=new qR(e,t,s,new WR(r)),this.assurances=new xR(e,t),this.accumulate=new CR(e,t),this.deferredTransfers=new HR(e,t),this.preimages=new JB(t),this.authorization=new VR(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 a=r;if(s&&(a=qe(i.seal).asOpaque()),null===a){const t=await this.verifySeal(n,e);if(t.isError)return XR(YR.SafroleSeal,t);a=t.ok}const o=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(o.isError)return XR(YR.Disputes,o);const{stateUpdate:{disputesRecords:c,availabilityAssignment:l,...d},offendersMark:u}=o.ok;C(d);const h=function(e,t){if(e.size!==t.length)return D.error(JR,`Length mismatch: ${e.size} vs ${t.length}`);for(const r of t)if(!e.has(r))return D.error(JR,`Missing key: ${r}`);return D.ok(O)}(u,e.header.view().offendersMarker.materialize());if(h.isError)return XR(YR.Offenders,h);const f=await this.safrole.transition({slot:n,entropy:a,extrinsic:e.extrinsic.view().tickets.materialize(),punishSet:c.punishSet});if(f.isError)return XR(YR.Safrole,f);const{timeslot:g,ticketsAccumulator:p,sealingKeySeries:b,epochRoot:m,entropy:y,nextValidatorData:A,currentValidatorData:I,previousValidatorData:v,...w}=f.ok.stateUpdate;C(w);const S=this.recentHistory.partialTransition({priorStateRoot:i.priorStateRoot}),{recentBlocks:E,...k}=S;C(k);const B=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash,disputesAvailAssignment:l});if(B.isError)return XR(YR.Assurances,B);const{availableReports:_,stateUpdate:R,...U}=B.ok;C(U);const{availabilityAssignment:T,...N}=R;C(N);const M=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),newEntropy:y,recentBlocksPartialUpdate:E,assurancesAvailAssignment:T,offenders:u});if(M.isError)return XR(YR.Reports,M);const{reported:P,reporters:L,stateUpdate:H,...V}=M.ok;C(V);const{availabilityAssignment:K,...Q}=H;C(Q);const F=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(F.isError)return XR(YR.Preimages,F);const{preimages:$,...G}=F.ok;C(G);const j=x("import:accumulate"),q=await this.accumulate.transition({slot:n,reports:_,entropy:y[0]});if(ZR.log(j()),q.isError)return XR(YR.Accumulate,q);const{root:z,stateUpdate:W,accumulationStatistics:J,pendingTransfers:Y,...X}=q.ok;C(X);const{privilegedServices:Z,authQueues:ee,designatedValidatorData:te,timeslot:re,preimages:se,accumulationQueue:ie,recentlyAccumulated:ne,...ae}=W,oe=await this.deferredTransfers.transition({entropy:y[0],pendingTransfers:Y,servicesUpdate:{...ae,preimages:se},timeslot:n});if(oe.isError)return XR(YR.DeferredTransfers,oe);const{servicesUpdate:ce,transferStatistics:le,...de}=oe.ok;C(de);const ue=this.recentHistory.transition({partial:S,headerHash:t,accumulateRoot:z,workPackages:P}),{recentBlocks:he,...fe}=ue;C(fe);const ge=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:pe,...be}=ge;C(be);const me=e.extrinsic.materialize(),ye=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:me,incomingReports:me.guarantees.map(e=>e.report),availableReports:_,accumulationStatistics:J,transferStatistics:le}),{statistics:Ae,...Ie}=ye;return C(Ie),D.ok({...void 0!==ee?{authQueues:ee}:{},...void 0!==te?{designatedValidatorData:te}:{},...void 0!==Z?{privilegedServices:Z}:{},authPools:pe,disputesRecords:c,availabilityAssignment:K,recentBlocks:he,statistics:Ae,timeslot:g,epochRoot:m,entropy:y,currentValidatorData:I,nextValidatorData:A,previousValidatorData:v,sealingKeySeries:b,ticketsAccumulator:p,accumulationQueue:ie,recentlyAccumulated:ne,...ce,preimages:$.concat(se)})}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)??bt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}var tO;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(tO||(tO={}));const rO=(e,t)=>D.taggedError(tO,e,t);class sO{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(),a=i.getState(n);if(null===a)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new ZB(t,s),this.stf=new eO(e,a,s,t,{enableParallelSealVerification:!0}),this.state=a,r.info(`😎 Best time slot: ${a.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: ${N(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=x("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return rO(tO.Verifier,n);const a=e.header.view().timeSlotIndex.materialize(),o=n.ok;s.log(`🧱 Verified block: Got hash ${o} for block at slot ${a}.`);const c=x("import:stf"),l=await this.stf.transition(e,o,t,r);if(s.log(c()),l.isError)return rO(tO.Stf,l);const d=l.ok,u=x("import:state"),h=await this.states.updateAndSetState(o,this.state,d);if(h.isError)return s.error(`🧱 Unable to update state: ${N(h)}`),rO(tO.Update,h);const f=this.states.getState(o);if(null===f)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(f.backend),s.log(u());const g=x("import:db"),p=this.blocks.insertBlock(new He(o,e)),b=await this.states.getStateRoot(f);s.log(`🧱 Storing post-state-root for ${o}: ${b}.`);const m=this.blocks.setPostStateRoot(o,b);return await Promise.all([p,m]),s.log(g()),await this.blocks.setBestHeaderHash(o),D.ok(new He(o,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const iO=Zs.new(void 0,"importer");class nO extends fk{onBestBlock=new dk;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=fe.decodeObject(gs,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 aO extends fk{onBlock=new dk;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=Ae.encodeObject(gs,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(ys.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else iO.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 oO=Zs.new(void 0,"importer");if(!vE.isMainThread){Zs.configureAll(process.env.JAM_LOG??"",$s.LOG);const e=function(){const e=new bk("ready(importer)",Ct.reInit),t=new aO,r=new gk;return new uk("importer",e,[e,t,r])}();ok.receiveChannel(e,vE.parentPort).then(e=>async function(e){oO.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{oO.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new xE(r.dbPath),i=new SE(r.chainSpec,s),n=new ek(r.chainSpec,s),a=new sO(r.chainSpec,new WB(r.chainSpec,await cO,new Ke),oO,i,n);let o=!1;const c=new YB(r.chainSpec,a);e.onBlock.on(async s=>{const n=YB.getBlockDetails(s);if(n.isError)oO.trace("🧊 Ignoring invalid block.");else if(null===i.getHeader(n.ok.hash)){if(c.push(n.ok).isError)oO.trace(`🧊 Already queued block: #${n.ok.data.timeSlot}.`);else if(oO.log(`🧊 Queued block: #${n.ok.data.timeSlot}`),!o){o=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:o}=s,l=x("importBlock"),d=await a.importBlock(i,await n,r.omitSealVerification);if(d.isOk){const r=d.ok;e.announce(t,r),oO.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else oO.log(`❌ Rejected block #${o}: ${N(d)}`);oO.log(l())}}finally{o=!1}}}else oO.trace(`🧊 Already imported block: #${n.ok.data.timeSlot}.`)})});oO.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>oO.error(e))}const cO=ft.create(),lO=Zs.new(void 0,"net:worker");class dO{genericConfig;genesisHeaderHash;key;host;port;bootnodes;static reInit(e){const{genericConfig:t,genesisHeaderHash:r,key:s,host:i,port:n,bootnodes:a}=e;return new dO(Ct.reInit(t),L.fromBlob(r.raw,Pe).asOpaque(),L.fromBlob(s.raw,32).asOpaque(),i,n,a)}static new({genericConfig:e,genesisHeaderHash:t,key:r,host:s,port:i,bootnodes:n}){return new dO(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.genericConfig=e,this.genesisHeaderHash=t,this.key=r,this.host=s,this.port=i,this.bootnodes=n}}class uO extends fk{onNewBlocks=new dk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{newBlocks:e=>this.triggerNewBlocks(e)}})}triggerNewBlocks(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(Be.sequenceVarLen(ys.Codec.View),e,t.genericConfig.chainSpec);this.onNewBlocks.emit(r)}else lO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}announceHeader(e,t){const r=Ae.encodeObject(gs,t);e.sendSignal("announceHeader",r.raw,[r.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive network config!");return this.data}finish(e){return this.onNewBlocks.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class hO extends fk{onNewHeader=new dk;constructor(){super({name:"ready(network)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{announceHeader:e=>this.triggerHeaderAnnouncement(e)}})}triggerHeaderAnnouncement(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(gs,e,t.genericConfig.chainSpec);this.onNewHeader.emit(r)}else lO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}sendBlocks(e,t){const r=this.getConfig(),s=Ae.encodeObject(Be.sequenceVarLen(ys.Codec.View),t,r.genericConfig.chainSpec);e.sendSignal("newBlocks",s.raw,[s.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}class fO{chainSpec;keccakHasher;blocks;states;hashAllocator=new Ke;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:a}=fO.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=a}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=fO.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 Ae.encodeObject(ys.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Tr(e%6),r=new WB(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=ms.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:Or.create({verdicts:[],culprits:[],faults:[]})}),a=Ae.encodeObject(ms.Codec,n,this.chainSpec),o=fe.decodeObject(ms.Codec.View,a,this.chainSpec),c=r.extrinsic(o).hash,l=L.zero(Ne),d=Ae.create({destination:l.raw});d.i32(e),d.i16(t);const u=hs.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Ur(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:L.fill(Ne,42*e%256).asOpaque(),seal:l.asOpaque()}),h=Ae.encodeObject(hs.Codec,u,this.chainSpec),f=fe.decodeObject(hs.Codec.View,h,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,ys.create({header:u,extrinsic:n})}}const gO=Zs.new(void 0,"block-generator");class pO extends fk{onBlock=new dk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):gO.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 bO extends fk{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 mO=Zs.new(void 0,"block-generator");if(!vE.isMainThread){Zs.configureAll(process.env.JAM_LOG??"",$s.LOG);const e=function(){const e=new bk("ready(generator)",Ct.reInit),t=new bO,r=new gk;return new uk("block-generator",e,[e,t,r])}();ok.receiveChannel(e,vE.parentPort).then(e=>async function(e){mO.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new xE(r.dbPath),i=new SE(r.chainSpec,s),n=new ek(r.chainSpec,s),a=await t.doUntil("finished",async(e,t,s)=>{let a=0;const o=new fO(r.chainSpec,await ft.create(),i,n);for(;!s();){await(0,Fs.setTimeout)(1e3*r.chainSpec.slotDuration),a+=1;const s=await o.nextEncodedBlock();mO.trace(`Sending block ${a}`),e.sendBlock(t,s)}});mO.info("Block Generator finished. Closing channel."),a.currentState().close(e)}(e)).catch(e=>{mO.error(e),void 0!==e.stack&&mO.error(e.stack),void 0!==e.cause&&mO.error(e.cause)})}const yO=t(import.meta.url)("node:net"),AO=t(import.meta.url)("node:path");class IO{socket;constructor(e){this.socket=e}send(e){!function(e,t){e.write(pS(t)),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}var vO;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(vO||(vO={}));class wO{streamId;type;data;static Codec=Be.Class(wO,{streamId:Be.u32,type:Be.u8.convert(e=>te(e),e=>{switch(e){case vO.Msg:return vO.Msg;case vO.Open:return vO.Open;case vO.Close:return vO.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:Be.blob});static create({streamId:e,type:t,data:r}){return new wO(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class SO{streamByte;static Codec=Be.Class(SO,{streamByte:Be.u8});static create({streamByte:e}){return new SO(e)}constructor(e){this.streamByte=e}}const EO=Zs.new(void 0,"ext-ipc");class CO{sender;streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;constructor(e){this.sender=e;let t=()=>{},r=e=>{};const s=new Promise((e,s)=>{t=e,r=s});this.onEnd={finished:!1,listen:s,resolve:t,reject:r}}registerStreamHandlers(...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 kO(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 kO(i,this.sender);n.open(SO.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=fe.decodeObject(wO.Codec,e),r=t.streamId;EO.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new kO(r,this.sender);if(void 0===s){if(t.type!==vO.Open)return void EO.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=fe.decodeObject(SO.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(EO.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===vO.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===vO.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||EO.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){EO.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 EO.log("Waiting for the handler to be closed."),this.onEnd.listen}}class kO{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Ae.encodeObject(SO.Codec,e);this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Open,data:t})))}bufferAndSend(e){return this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Msg,data:e}))),!0}close(){this.sender.send(Ae.encodeObject(wO.Codec,wO.create({streamId:this.streamId,type:vO.Close,data:P.blobFromNumbers([])})))}}function xO(e,t,r,s,i){return function(n){const a="win32"===dE.platform()?`\\\\.\\pipe\\${n}`:AO.join(dE.tmpdir(),`${n}.ipc`),o=Zs.new(void 0,"ext-ipc"),d=(0,yO.createServer)(n=>{o.log("Client connected");const a=(n=>{const a=new CO(n),o=e=>{if(!(e instanceof c.Announcement))throw new Error(`Invalid annoncement received: ${e}`);a.withStreamOfKind(c.STREAM_KIND,(t,r)=>{t.sendAnnouncement(r,e)})};return t.on(o),a.waitForEnd().finally(()=>{t.off(o)}),a.registerStreamHandlers(new c.Handler(e,r,()=>{},()=>{})),a.registerStreamHandlers(new l.Handler(!0,s,i)),a})(new IO(n));n.on("data",bS(e=>{try{a.onSocketMessage(e)}catch(e){o.error(`Received invalid data on socket: ${e}. Closing connection.`),n.end()}},()=>{o.error("Received too much data on socket. Closing connection."),n.end()})),n.on("end",()=>{o.log("Client disconnected"),a.onClose({})}),n.on("error",e=>{o.error(`Socket error: ${e}`),a.onClose({error:e}),n.end()})});try{cE.unlinkSync(a)}catch{}const u=new AbortController;return d.listen({path:a,signal:u.signal},()=>{o.log(`IPC server is listening at ${a}`)}),d.on("error",e=>{throw e}),()=>{o.info("Closing IPC server."),d.close(),u.abort(),d.unref()}}("typeberry-jamnp")}const BO=Zs.new(void 0,"net");if(!vE.isMainThread){Zs.configureAll(process.env.JAM_LOG??"",$s.LOG);const e=function(){const e=new bk("ready(network)",dO.reInit),t=new hO,r=new gk;return new uk("network",e,[e,t,r])}();ok.receiveChannel(e,vE.parentPort).then(e=>async function(e){BO.trace(`🛜 Network starting ${e.currentState()}`);const t=await e.waitForState("ready(network)"),r=await t.doUntil("finished",async(e,r)=>{const s=e.getConfig(),i=await Ir(s.key),n=new xE(s.genericConfig.dbPath),a=new SE(s.genericConfig.chainSpec,n);BO.info(`🛜 Listening at ${s.host}:${s.port}`);const o=await async function(e,t,r,s,i,n,a){const o=t.toString().substring(2,10),c=await fS.setup({host:e.host,port:e.port,key:r,protocols:[`jamnp-s/0/${o}`]}),l=new AS(c);l.addPersistentRetry(s);const d=new SS,u=sE.start(i,d,l,n,a);return setImmediate(async()=>{for(;c.isRunning;)await(0,Fs.setTimeout)(3e3),u.maintainSync()}),function(e,t,r){t.peers.onPeerConnected(t=>(t.addOnIncomingStream(e=>(vS(()=>r.onIncomingStream(t,e),r=>{nE.error(`[${t.id}:${e.streamId}]🚰 Stream error: ${r}. Disconnecting peer.`),t.disconnect()}),O)),e.openUp0(t),O))}(u,c,d),{network:c,syncTask:u,streamManager:d}}({host:s.host,port:s.port},s.genesisHeaderHash,i,s.bootnodes.map(aE).filter(e=>e.host!==s.host||e.port!==s.port),s.genericConfig.chainSpec,a,t=>e.sendBlocks(r,t));e.onNewHeader.on(e=>{o.syncTask.broadcastHeader(e)}),t.waitForState("finished").then(()=>o.network.stop()),await o.network.start()});BO.info("🛜 Network worker finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>BO.error(e))}const _O=e=>e.endsWith(".json");function RO(e,t){const r=lE().readFileSync(e),s=P.blobFrom(new Uint8Array(r));return fe.decodeObject(ys.Codec.View,s,t)}function OO(e,t){const r=lE().readFileSync(e,"utf-8"),s=JSON.parse(r),i=X("block"in s?s.block:s,(n=t,ee.object({header:Qs,extrinsic:(a=n,ee.object({tickets:Ps,preimages:Ds,guarantees:Ts,assurances:kr(a),disputes:Ss},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>ms.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>ys.create({header:e,extrinsic:t}))));var n,a;const o=Ae.encodeObject(ys.Codec,i,t);return fe.decodeObject(ys.Codec.View,o,t)}const UO={genesisPath:"",timeSlot:Ur(0),validatorIndex:Tr(0)};class TO{isAuthoring;blocksToImport;nodeName;node;dev;network;static new({isAuthoring:e,blocksToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n,networkConfig:a}){let o=i??{...UO};return void 0!==n&&(o={...o,...n}),new TO(e??!1,t??null,r,s,o,a??null)}constructor(e,t,r,s,i,n){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i,this.network=n}}const NO=Zs.new(void 0,"jam");var DO;async function MO(e,t){if(!vE.isMainThread)return void NO.error("The main binary cannot be running as a Worker!");NO.info(`🫐 Typeberry 0.0.1. GP: ${A} (${I})`),NO.info(`🎸 Starting node: ${e.nodeName}.`);const r=VO(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=ze(e).toString().substring(2,10),n=qe(t).asOpaque(),a=`${r}/${i}/${n.toString().substring(2,10)}`;NO.info(`🛢️ Opening database at ${a}`);try{return{dbPath:a,rootDb:new xE(a,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${a}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new SE(e,r),n=new ek(e,r),a=i.getBestHeaderHash(),o=i.getPostStateRoot(a);if(NO.log(`🛢️ Best header hash: ${a}`),NO.log(`🛢️ Best state root: ${o}`),null!==o&&!o.isEqualTo(L.zero(Pe))&&!a.isEqualTo(L.zero(Pe)))return void await r.db.close();NO.log("🛢️ Database looks fresh. Initializing.");const c=fe.decodeObject(hs.Codec,s.genesisHeader,e),l=ys.create({header:hs.empty(),extrinsic:ms.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,d=ys.create({header:c,extrinsic:l}),u=fe.decodeObject(ys.Codec.View,Ae.encodeObject(ys.Codec,d,e),e);NO.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:h,genesisStateRootHash:f}=function(e,t){const r=$C.fromEntriesUnsafe(t.entries()),s=TC.fromStateEntries(e,r),i=r.getRootHash();return NO.info(`🧬 Genesis state root: ${i}`),{genesisState:s,genesisStateSerialized:r,genesisStateRootHash:i}}(e,s.genesisState);await i.insertBlock(new He(t,u)),await n.insertState(t,h),await i.setPostStateRoot(t,f),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const a=await async function(){const e=oO,t=new nO;return mk(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),o=a.getState("ready(main)").onBestBlock,d=function(e){const t=function(e){const t=function(e){const t=new dk;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=c.HashAndSlot.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit(c.Announcement.create({header:s,final:n}))}),xO(e.chainSpec,t,()=>{const e=r??c.HashAndSlot.create({hash:L.zero(Pe).asOpaque(),slot:Ur(0)});return c.Handshake.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=P.blobFromNumbers([255,255,0,0]);return L.fromBlob(ze("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,Le),Le).isEqualTo(t)&&(r=P.blobFromNumbers([255,255,255,0])),[new l.KeyValuePair(t,r)]})}(e);return()=>{t()}}(e);return()=>{t()}}({chainSpec:r,bestHeader:o}),u=new Ct(r,i,e.node.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,u)),f=LO(h,r,e.blocksToImport),g=await PO(h,e.isAuthoring&&null===e.blocksToImport,u),p=await HO(h,u,n,e.network,null===e.blocksToImport,o);NO.info("[main]⌛ waiting for importer to finish");const b=await f;NO.log("[main] ☠️ Closing the extensions"),d(),NO.log("[main]⌛ waiting for tasks to finish"),await b.currentState().waitForWorkerToFinish(),NO.log("[main] ☠️ Closing the authorship module"),g(),NO.log("[main] ☠️ Closing the networking module"),p(),NO.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(DO||(DO={}));const PO=async(e,t,r)=>{if(!t)return NO.log("✍️ Authorship off: disabled"),()=>Promise.resolve();NO.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=mO,t=new pO;return mk(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"))}}(r);return e.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{NO.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},LO=async(e,t,r)=>null===r?e.waitForState("finished"):(NO.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=_O(r)?OO(r,t):RO(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)NO.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return NO.info("All blocks scheduled to be imported."),e.finish(s)})),HO=async(e,t,r,s,i,n)=>{if(!i||null===s)return NO.log("🛜 Networking off: "+(null===s?"no config":"disabled")),()=>Promise.resolve();const{key:o,host:c,port:l,bootnodes:d}=s,{network:u,finish:h}=await async function(e){const t=(await async function(){return mk(new URL(a(493),a.b),BO,"ready(main)",new uO)}()).transition((t,r)=>t.sendConfig(r,e));return{network:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(dO.new({genericConfig:t,genesisHeaderHash:r,key:o,host:c,port:l,bootnodes:d.map(e=>e.toString())}));return e.doUntil("finished",async(e,t)=>{u.currentState().onNewBlocks.on(r=>{for(const s of r)e.sendBlock(t,s.encoded().raw)})}),u.doUntil("finished",async(e,t)=>{n.on(r=>{e.announceHeader(t,r)})}),h},VO=e=>{if(e===yE.Full)return Et;if(e===yE.Tiny)return St;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[yE.Full,yE.Tiny]}`)},KO=(e=>{var t={};return a.d(t,e),t})({default:()=>s.default}),QO=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] dev <dev-validator-index>\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${mE.name}]\n --config Path to a config file or one of: ['${pE}', '${bE}'].\n [default: ${mE.config}]\n`;var FO;function $O(e,t){const{name:r}=jO(e,"name",e=>e,mE.name),{config:s}=jO(e,"config",e=>e===pE?pE:t(e),mE.config);return{nodeName:r,configPath:s}}function GO(e,t){const r=(0,KO.default)(e),s=r._.shift()??FO.Run;switch(s){case FO.Run:{const e=$O(r,t);return qO(r),{command:FO.Run,args:e}}case FO.Dev:{const e=$O(r,t),s=r._.shift();if(void 0===s)throw new Error("Missing dev-validator index.");const i=Number(s);if(!ie(i))throw new Error(`Invalid dev-validator index: ${i}, need U16`);return qO(r),{command:FO.Dev,args:{...e,index:i}}}case FO.Import:{const e=$O(r,t),s=r._.map(e=>t(e));return r._=[],qO(r),{command:FO.Import,args:{...e,files:s}}}default:r._.unshift(s),qO(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function jO(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 qO(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.Dev="dev",e.Import="import"}(FO||(FO={}));const zO=e=>{const t=e.command===FO.Import?e.args.files:null,r=function(e){if(e===bE)return X(hE,IE.fromJson);if(e===pE)return X(fE,IE.fromJson);try{const t=lE().readFileSync(e,"utf8");return X(JSON.parse(t),IE.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath),s=e.command===FO.Dev?`${e.args.nodeName}-${e.args.index}`:e.args.nodeName,i=e.command===FO.Dev?e.args.index:0,n=function(e,t=new Ke){return qe(P.blobFromParts([Sr.raw,e.raw]),t).asOpaque()}(ze(s).asOpaque());return TO.new({isAuthoring:e.command===FO.Dev,nodeName:s,blocksToImport:t,nodeConfig:r,networkConfig:{key:n,host:"127.0.0.1",port:12345+i,bootnodes:r.chainSpec.bootnodes??[]}})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,d.pathToFileURL)(process.argv[1]).href){Zs.configureAll(process.env.JAM_LOG??"",$s.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=GO(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(QO),process.exit(1)}MO(zO(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let WO;Zs.configureAll(process.env.JAM_LOG??"",$s.LOG);try{WO=GO(process.argv.slice(2),JO)}catch(e){console.error(`\n${e}\n`),console.info(QO),process.exit(1)}function JO(e){return e}MO(zO(WO),JO).catch(e=>{console.error(`${e}`),process.exit(-1)});export{FO as Command,QO as HELP,GO as parseArgs,zO as prepareConfigFile};
|
|
3
3
|
//# sourceMappingURL=typeberry.mjs.map
|