@smartledger/bsv 7.5.1 → 7.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bsv-gdaf.min.js CHANGED
@@ -14,7 +14,7 @@ Use Chrome, Firefox or Internet Explorer 11`)}var qU=nt().Buffer,od=globalThis.c
14
14
  `)}});var xO=k(SO=>{v();var wO=SO;wO.der=Tm();wO.pem=_O()});var Tc=k(EO=>{v();var Bc=EO;Bc.bignum=Nn();Bc.define=YE().define;Bc.base=Rc();Bc.constants=Sm();Bc.decoders=pO();Bc.encoders=xO()});var PO=k((O1e,AO)=>{"use strict";v();var Dn=Tc(),OO=Dn.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),mY=Dn.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),Bm=Dn.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),yY=Dn.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(Bm),this.key("subjectPublicKey").bitstr())}),bY=Dn.define("RelativeDistinguishedName",function(){this.setof(mY)}),_Y=Dn.define("RDNSequence",function(){this.seqof(bY)}),IO=Dn.define("Name",function(){this.choice({rdnSequence:this.use(_Y)})}),wY=Dn.define("Validity",function(){this.seq().obj(this.key("notBefore").use(OO),this.key("notAfter").use(OO))}),SY=Dn.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),xY=Dn.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(Bm),this.key("issuer").use(IO),this.key("validity").use(wY),this.key("subject").use(IO),this.key("subjectPublicKeyInfo").use(yY),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(SY).optional())}),EY=Dn.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(xY),this.key("signatureAlgorithm").use(Bm),this.key("signatureValue").bitstr())});AO.exports=EY});var kO=k(qn=>{"use strict";v();var Ln=Tc();qn.certificate=PO();var OY=Ln.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});qn.RSAPrivateKey=OY;var IY=Ln.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});qn.RSAPublicKey=IY;var TO=Ln.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),AY=Ln.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(TO),this.key("subjectPublicKey").bitstr())});qn.PublicKey=AY;var PY=Ln.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(TO),this.key("subjectPrivateKey").octstr())});qn.PrivateKey=PY;var TY=Ln.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});qn.EncryptedPrivateKey=TY;var kY=Ln.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});qn.DSAPrivateKey=kY;qn.DSAparam=Ln.define("DSAparam",function(){this.int()});var RY=Ln.define("ECParameters",function(){this.choice({namedCurve:this.objid()})}),BY=Ln.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(RY),this.key("publicKey").optional().explicit(1).bitstr())});qn.ECPrivateKey=BY;qn.signature=Ln.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})});var RO=k((T1e,MY)=>{MY.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}});var MO=k((k1e,BO)=>{"use strict";v();var NY=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,CY=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,DY=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,LY=Xh(),qY=q2(),V2=nt().Buffer;BO.exports=function(e,t){var r=e.toString(),i=r.match(NY),n;if(i){var a="aes"+i[1],s=V2.from(i[2],"hex"),u=V2.from(i[3].replace(/[\r\n]/g,""),"base64"),c=LY(t,s.slice(0,8),parseInt(i[1],10)).key,l=[],m=qY.createDecipheriv(a,c,s);l.push(m.update(u)),l.push(m.final()),n=V2.concat(l)}else{var o=r.match(DY);n=V2.from(o[2].replace(/[\r\n]/g,""),"base64")}var w=r.match(CY)[1];return{tag:w,data:n}}});var Nm=k((B1e,CO)=>{"use strict";v();var Ti=kO(),UY=RO(),FY=MO(),HY=q2(),jY=zv().pbkdf2Sync,Mm=nt().Buffer;function zY(e,t){var r=e.algorithm.decrypt.kde.kdeparams.salt,i=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),n=UY[e.algorithm.decrypt.cipher.algo.join(".")],o=e.algorithm.decrypt.cipher.iv,a=e.subjectPrivateKey,s=parseInt(n.split("-")[1],10)/8,u=jY(t,r,i,s,"sha1"),c=HY.createDecipheriv(n,u,o),l=[];return l.push(c.update(a)),l.push(c.final()),Mm.concat(l)}function NO(e){var t;typeof e=="object"&&!Mm.isBuffer(e)&&(t=e.passphrase,e=e.key),typeof e=="string"&&(e=Mm.from(e));var r=FY(e,t),i=r.tag,n=r.data,o,a;switch(i){case"CERTIFICATE":a=Ti.certificate.decode(n,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(a||(a=Ti.PublicKey.decode(n,"der")),o=a.algorithm.algorithm.join("."),o){case"1.2.840.113549.1.1.1":return Ti.RSAPublicKey.decode(a.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return a.subjectPrivateKey=a.subjectPublicKey,{type:"ec",data:a};case"1.2.840.10040.4.1":return a.algorithm.params.pub_key=Ti.DSAparam.decode(a.subjectPublicKey.data,"der"),{type:"dsa",data:a.algorithm.params};default:throw new Error("unknown key id "+o)}case"ENCRYPTED PRIVATE KEY":n=Ti.EncryptedPrivateKey.decode(n,"der"),n=zY(n,t);case"PRIVATE KEY":switch(a=Ti.PrivateKey.decode(n,"der"),o=a.algorithm.algorithm.join("."),o){case"1.2.840.113549.1.1.1":return Ti.RSAPrivateKey.decode(a.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:a.algorithm.curve,privateKey:Ti.ECPrivateKey.decode(a.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return a.algorithm.params.priv_key=Ti.DSAparam.decode(a.subjectPrivateKey,"der"),{type:"dsa",params:a.algorithm.params};default:throw new Error("unknown key id "+o)}case"RSA PUBLIC KEY":return Ti.RSAPublicKey.decode(n,"der");case"RSA PRIVATE KEY":return Ti.RSAPrivateKey.decode(n,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:Ti.DSAPrivateKey.decode(n,"der")};case"EC PRIVATE KEY":return n=Ti.ECPrivateKey.decode(n,"der"),{curve:n.parameters.value,privateKey:n.privateKey};default:throw new Error("unknown key type "+i)}}NO.signature=Ti.signature;CO.exports=NO});var Dm=k((N1e,DO)=>{v();var KY=zh(),Cm=nt().Buffer;DO.exports=function(e,t){for(var r=Cm.alloc(0),i=0,n;r.length<t;)n=VY(i++),r=Cm.concat([r,KY("sha1").update(e).update(n).digest()]);return r.slice(0,t)};function VY(e){var t=Cm.allocUnsafe(4);return t.writeUInt32BE(e,0),t}});var Lm=k((D1e,LO)=>{v();LO.exports=function(t,r){for(var i=t.length,n=-1;++n<i;)t[n]^=r[n];return t}});var qm=k((q1e,UO)=>{v();var qO=Nn(),GY=nt().Buffer;function ZY(e,t){return GY.from(e.toRed(qO.mont(t.modulus)).redPow(new qO(t.publicExponent)).fromRed().toArray())}UO.exports=ZY});var HO=k((FO,Um)=>{v();(function(e,t){"use strict";function r(y,f){if(!y)throw new Error(f||"Assertion failed")}function i(y,f){y.super_=f;var d=function(){};d.prototype=f.prototype,y.prototype=new d,y.prototype.constructor=y}function n(y,f,d){if(n.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((f==="le"||f==="be")&&(d=f,f=10),this._init(y||0,f||10,d||"be"))}typeof e=="object"?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Kt().Buffer}catch{}n.isBN=function(f){return f instanceof n?!0:f!==null&&typeof f=="object"&&f.constructor.wordSize===n.wordSize&&Array.isArray(f.words)},n.max=function(f,d){return f.cmp(d)>0?f:d},n.min=function(f,d){return f.cmp(d)<0?f:d},n.prototype._init=function(f,d,_){if(typeof f=="number")return this._initNumber(f,d,_);if(typeof f=="object")return this._initArray(f,d,_);d==="hex"&&(d=16),r(d===(d|0)&&d>=2&&d<=36),f=f.toString().replace(/\s+/g,"");var x=0;f[0]==="-"&&(x++,this.negative=1),x<f.length&&(d===16?this._parseHex(f,x,_):(this._parseBase(f,d,x),_==="le"&&this._initArray(this.toArray(),d,_)))},n.prototype._initNumber=function(f,d,_){f<0&&(this.negative=1,f=-f),f<67108864?(this.words=[f&67108863],this.length=1):f<4503599627370496?(this.words=[f&67108863,f/67108864&67108863],this.length=2):(r(f<9007199254740992),this.words=[f&67108863,f/67108864&67108863,1],this.length=3),_==="le"&&this._initArray(this.toArray(),d,_)},n.prototype._initArray=function(f,d,_){if(r(typeof f.length=="number"),f.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(f.length/3),this.words=new Array(this.length);for(var x=0;x<this.length;x++)this.words[x]=0;var b,p,I=0;if(_==="be")for(x=f.length-1,b=0;x>=0;x-=3)p=f[x]|f[x-1]<<8|f[x-2]<<16,this.words[b]|=p<<I&67108863,this.words[b+1]=p>>>26-I&67108863,I+=24,I>=26&&(I-=26,b++);else if(_==="le")for(x=0,b=0;x<f.length;x+=3)p=f[x]|f[x+1]<<8|f[x+2]<<16,this.words[b]|=p<<I&67108863,this.words[b+1]=p>>>26-I&67108863,I+=24,I>=26&&(I-=26,b++);return this._strip()};function a(y,f){var d=y.charCodeAt(f);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;r(!1,"Invalid character in "+y)}function s(y,f,d){var _=a(y,d);return d-1>=f&&(_|=a(y,d-1)<<4),_}n.prototype._parseHex=function(f,d,_){this.length=Math.ceil((f.length-d)/6),this.words=new Array(this.length);for(var x=0;x<this.length;x++)this.words[x]=0;var b=0,p=0,I;if(_==="be")for(x=f.length-1;x>=d;x-=2)I=s(f,d,x)<<b,this.words[p]|=I&67108863,b>=18?(b-=18,p+=1,this.words[p]|=I>>>26):b+=8;else{var T=f.length-d;for(x=T%2===0?d+1:d;x<f.length;x+=2)I=s(f,d,x)<<b,this.words[p]|=I&67108863,b>=18?(b-=18,p+=1,this.words[p]|=I>>>26):b+=8}this._strip()};function u(y,f,d,_){for(var x=0,b=0,p=Math.min(y.length,d),I=f;I<p;I++){var T=y.charCodeAt(I)-48;x*=_,T>=49?b=T-49+10:T>=17?b=T-17+10:b=T,r(T>=0&&b<_,"Invalid character"),x+=b}return x}n.prototype._parseBase=function(f,d,_){this.words=[0],this.length=1;for(var x=0,b=1;b<=67108863;b*=d)x++;x--,b=b/d|0;for(var p=f.length-_,I=p%x,T=Math.min(p,p-I)+_,S=0,R=_;R<T;R+=x)S=u(f,R,R+x,d),this.imuln(b),this.words[0]+S<67108864?this.words[0]+=S:this._iaddn(S);if(I!==0){var Y=1;for(S=u(f,R,f.length,d),R=0;R<I;R++)Y*=d;this.imuln(Y),this.words[0]+S<67108864?this.words[0]+=S:this._iaddn(S)}this._strip()},n.prototype.copy=function(f){f.words=new Array(this.length);for(var d=0;d<this.length;d++)f.words[d]=this.words[d];f.length=this.length,f.negative=this.negative,f.red=this.red};function c(y,f){y.words=f.words,y.length=f.length,y.negative=f.negative,y.red=f.red}if(n.prototype._move=function(f){c(f,this)},n.prototype.clone=function(){var f=new n(null);return this.copy(f),f},n.prototype._expand=function(f){for(;this.length<f;)this.words[this.length++]=0;return this},n.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},n.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{n.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch{n.prototype.inspect=l}else n.prototype.inspect=l;function l(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var m=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],w=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],E=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];n.prototype.toString=function(f,d){f=f||10,d=d|0||1;var _;if(f===16||f==="hex"){_="";for(var x=0,b=0,p=0;p<this.length;p++){var I=this.words[p],T=((I<<x|b)&16777215).toString(16);b=I>>>24-x&16777215,x+=2,x>=26&&(x-=26,p--),b!==0||p!==this.length-1?_=m[6-T.length]+T+_:_=T+_}for(b!==0&&(_=b.toString(16)+_);_.length%d!==0;)_="0"+_;return this.negative!==0&&(_="-"+_),_}if(f===(f|0)&&f>=2&&f<=36){var S=w[f],R=E[f];_="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var X=Y.modrn(R).toString(f);Y=Y.idivn(R),Y.isZero()?_=X+_:_=m[S-X.length]+X+_}for(this.isZero()&&(_="0"+_);_.length%d!==0;)_="0"+_;return this.negative!==0&&(_="-"+_),_}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var f=this.words[0];return this.length===2?f+=this.words[1]*67108864:this.length===3&&this.words[2]===1?f+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-f:f},n.prototype.toJSON=function(){return this.toString(16,2)},o&&(n.prototype.toBuffer=function(f,d){return this.toArrayLike(o,f,d)}),n.prototype.toArray=function(f,d){return this.toArrayLike(Array,f,d)};var P=function(f,d){return f.allocUnsafe?f.allocUnsafe(d):new f(d)};n.prototype.toArrayLike=function(f,d,_){this._strip();var x=this.byteLength(),b=_||Math.max(1,x);r(x<=b,"byte array longer than desired length"),r(b>0,"Requested array length <= 0");var p=P(f,b),I=d==="le"?"LE":"BE";return this["_toArrayLike"+I](p,x),p},n.prototype._toArrayLikeLE=function(f,d){for(var _=0,x=0,b=0,p=0;b<this.length;b++){var I=this.words[b]<<p|x;f[_++]=I&255,_<f.length&&(f[_++]=I>>8&255),_<f.length&&(f[_++]=I>>16&255),p===6?(_<f.length&&(f[_++]=I>>24&255),x=0,p=0):(x=I>>>24,p+=2)}if(_<f.length)for(f[_++]=x;_<f.length;)f[_++]=0},n.prototype._toArrayLikeBE=function(f,d){for(var _=f.length-1,x=0,b=0,p=0;b<this.length;b++){var I=this.words[b]<<p|x;f[_--]=I&255,_>=0&&(f[_--]=I>>8&255),_>=0&&(f[_--]=I>>16&255),p===6?(_>=0&&(f[_--]=I>>24&255),x=0,p=0):(x=I>>>24,p+=2)}if(_>=0)for(f[_--]=x;_>=0;)f[_--]=0},Math.clz32?n.prototype._countBits=function(f){return 32-Math.clz32(f)}:n.prototype._countBits=function(f){var d=f,_=0;return d>=4096&&(_+=13,d>>>=13),d>=64&&(_+=7,d>>>=7),d>=8&&(_+=4,d>>>=4),d>=2&&(_+=2,d>>>=2),_+d},n.prototype._zeroBits=function(f){if(f===0)return 26;var d=f,_=0;return(d&8191)===0&&(_+=13,d>>>=13),(d&127)===0&&(_+=7,d>>>=7),(d&15)===0&&(_+=4,d>>>=4),(d&3)===0&&(_+=2,d>>>=2),(d&1)===0&&_++,_},n.prototype.bitLength=function(){var f=this.words[this.length-1],d=this._countBits(f);return(this.length-1)*26+d};function M(y){for(var f=new Array(y.bitLength()),d=0;d<f.length;d++){var _=d/26|0,x=d%26;f[d]=y.words[_]>>>x&1}return f}n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var f=0,d=0;d<this.length;d++){var _=this._zeroBits(this.words[d]);if(f+=_,_!==26)break}return f},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(f){return this.negative!==0?this.abs().inotn(f).iaddn(1):this.clone()},n.prototype.fromTwos=function(f){return this.testn(f-1)?this.notn(f).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return this.negative!==0},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(f){for(;this.length<f.length;)this.words[this.length++]=0;for(var d=0;d<f.length;d++)this.words[d]=this.words[d]|f.words[d];return this._strip()},n.prototype.ior=function(f){return r((this.negative|f.negative)===0),this.iuor(f)},n.prototype.or=function(f){return this.length>f.length?this.clone().ior(f):f.clone().ior(this)},n.prototype.uor=function(f){return this.length>f.length?this.clone().iuor(f):f.clone().iuor(this)},n.prototype.iuand=function(f){var d;this.length>f.length?d=f:d=this;for(var _=0;_<d.length;_++)this.words[_]=this.words[_]&f.words[_];return this.length=d.length,this._strip()},n.prototype.iand=function(f){return r((this.negative|f.negative)===0),this.iuand(f)},n.prototype.and=function(f){return this.length>f.length?this.clone().iand(f):f.clone().iand(this)},n.prototype.uand=function(f){return this.length>f.length?this.clone().iuand(f):f.clone().iuand(this)},n.prototype.iuxor=function(f){var d,_;this.length>f.length?(d=this,_=f):(d=f,_=this);for(var x=0;x<_.length;x++)this.words[x]=d.words[x]^_.words[x];if(this!==d)for(;x<d.length;x++)this.words[x]=d.words[x];return this.length=d.length,this._strip()},n.prototype.ixor=function(f){return r((this.negative|f.negative)===0),this.iuxor(f)},n.prototype.xor=function(f){return this.length>f.length?this.clone().ixor(f):f.clone().ixor(this)},n.prototype.uxor=function(f){return this.length>f.length?this.clone().iuxor(f):f.clone().iuxor(this)},n.prototype.inotn=function(f){r(typeof f=="number"&&f>=0);var d=Math.ceil(f/26)|0,_=f%26;this._expand(d),_>0&&d--;for(var x=0;x<d;x++)this.words[x]=~this.words[x]&67108863;return _>0&&(this.words[x]=~this.words[x]&67108863>>26-_),this._strip()},n.prototype.notn=function(f){return this.clone().inotn(f)},n.prototype.setn=function(f,d){r(typeof f=="number"&&f>=0);var _=f/26|0,x=f%26;return this._expand(_+1),d?this.words[_]=this.words[_]|1<<x:this.words[_]=this.words[_]&~(1<<x),this._strip()},n.prototype.iadd=function(f){var d;if(this.negative!==0&&f.negative===0)return this.negative=0,d=this.isub(f),this.negative^=1,this._normSign();if(this.negative===0&&f.negative!==0)return f.negative=0,d=this.isub(f),f.negative=1,d._normSign();var _,x;this.length>f.length?(_=this,x=f):(_=f,x=this);for(var b=0,p=0;p<x.length;p++)d=(_.words[p]|0)+(x.words[p]|0)+b,this.words[p]=d&67108863,b=d>>>26;for(;b!==0&&p<_.length;p++)d=(_.words[p]|0)+b,this.words[p]=d&67108863,b=d>>>26;if(this.length=_.length,b!==0)this.words[this.length]=b,this.length++;else if(_!==this)for(;p<_.length;p++)this.words[p]=_.words[p];return this},n.prototype.add=function(f){var d;return f.negative!==0&&this.negative===0?(f.negative=0,d=this.sub(f),f.negative^=1,d):f.negative===0&&this.negative!==0?(this.negative=0,d=f.sub(this),this.negative=1,d):this.length>f.length?this.clone().iadd(f):f.clone().iadd(this)},n.prototype.isub=function(f){if(f.negative!==0){f.negative=0;var d=this.iadd(f);return f.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(f),this.negative=1,this._normSign();var _=this.cmp(f);if(_===0)return this.negative=0,this.length=1,this.words[0]=0,this;var x,b;_>0?(x=this,b=f):(x=f,b=this);for(var p=0,I=0;I<b.length;I++)d=(x.words[I]|0)-(b.words[I]|0)+p,p=d>>26,this.words[I]=d&67108863;for(;p!==0&&I<x.length;I++)d=(x.words[I]|0)+p,p=d>>26,this.words[I]=d&67108863;if(p===0&&I<x.length&&x!==this)for(;I<x.length;I++)this.words[I]=x.words[I];return this.length=Math.max(this.length,I),x!==this&&(this.negative=1),this._strip()},n.prototype.sub=function(f){return this.clone().isub(f)};function D(y,f,d){d.negative=f.negative^y.negative;var _=y.length+f.length|0;d.length=_,_=_-1|0;var x=y.words[0]|0,b=f.words[0]|0,p=x*b,I=p&67108863,T=p/67108864|0;d.words[0]=I;for(var S=1;S<_;S++){for(var R=T>>>26,Y=T&67108863,X=Math.min(S,f.length-1),ne=Math.max(0,S-y.length+1);ne<=X;ne++){var ce=S-ne|0;x=y.words[ce]|0,b=f.words[ne]|0,p=x*b+Y,R+=p/67108864|0,Y=p&67108863}d.words[S]=Y|0,T=R|0}return T!==0?d.words[S]=T|0:d.length--,d._strip()}var L=function(f,d,_){var x=f.words,b=d.words,p=_.words,I=0,T,S,R,Y=x[0]|0,X=Y&8191,ne=Y>>>13,ce=x[1]|0,pe=ce&8191,q=ce>>>13,W=x[2]|0,$=W&8191,ee=W>>>13,se=x[3]|0,ue=se&8191,le=se>>>13,Ae=x[4]|0,ge=Ae&8191,ve=Ae>>>13,sr=x[5]|0,xe=sr&8191,ye=sr>>>13,Re=x[6]|0,be=Re&8191,_e=Re>>>13,Qi=x[7]|0,Me=Qi&8191,ke=Qi>>>13,$s=x[8]|0,Ce=$s&8191,Le=$s>>>13,$l=x[9]|0,qe=$l&8191,Ue=$l>>>13,Xl=b[0]|0,Fe=Xl&8191,He=Xl>>>13,Jl=b[1]|0,je=Jl&8191,ze=Jl>>>13,Ql=b[2]|0,Ke=Ql&8191,Ve=Ql>>>13,eh=b[3]|0,Ge=eh&8191,Ze=eh>>>13,th=b[4]|0,We=th&8191,Ye=th>>>13,rh=b[5]|0,$e=rh&8191,Xe=rh>>>13,ih=b[6]|0,Je=ih&8191,Qe=ih>>>13,nh=b[7]|0,et=nh&8191,tt=nh>>>13,oh=b[8]|0,rt=oh&8191,it=oh>>>13,Wf=b[9]|0,Jt=Wf&8191,Qt=Wf>>>13;_.negative=f.negative^d.negative,_.length=19,T=Math.imul(X,Fe),S=Math.imul(X,He),S=S+Math.imul(ne,Fe)|0,R=Math.imul(ne,He);var Xs=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(Xs>>>26)|0,Xs&=67108863,T=Math.imul(pe,Fe),S=Math.imul(pe,He),S=S+Math.imul(q,Fe)|0,R=Math.imul(q,He),T=T+Math.imul(X,je)|0,S=S+Math.imul(X,ze)|0,S=S+Math.imul(ne,je)|0,R=R+Math.imul(ne,ze)|0;var Js=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(Js>>>26)|0,Js&=67108863,T=Math.imul($,Fe),S=Math.imul($,He),S=S+Math.imul(ee,Fe)|0,R=Math.imul(ee,He),T=T+Math.imul(pe,je)|0,S=S+Math.imul(pe,ze)|0,S=S+Math.imul(q,je)|0,R=R+Math.imul(q,ze)|0,T=T+Math.imul(X,Ke)|0,S=S+Math.imul(X,Ve)|0,S=S+Math.imul(ne,Ke)|0,R=R+Math.imul(ne,Ve)|0;var Qs=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(Qs>>>26)|0,Qs&=67108863,T=Math.imul(ue,Fe),S=Math.imul(ue,He),S=S+Math.imul(le,Fe)|0,R=Math.imul(le,He),T=T+Math.imul($,je)|0,S=S+Math.imul($,ze)|0,S=S+Math.imul(ee,je)|0,R=R+Math.imul(ee,ze)|0,T=T+Math.imul(pe,Ke)|0,S=S+Math.imul(pe,Ve)|0,S=S+Math.imul(q,Ke)|0,R=R+Math.imul(q,Ve)|0,T=T+Math.imul(X,Ge)|0,S=S+Math.imul(X,Ze)|0,S=S+Math.imul(ne,Ge)|0,R=R+Math.imul(ne,Ze)|0;var eu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(eu>>>26)|0,eu&=67108863,T=Math.imul(ge,Fe),S=Math.imul(ge,He),S=S+Math.imul(ve,Fe)|0,R=Math.imul(ve,He),T=T+Math.imul(ue,je)|0,S=S+Math.imul(ue,ze)|0,S=S+Math.imul(le,je)|0,R=R+Math.imul(le,ze)|0,T=T+Math.imul($,Ke)|0,S=S+Math.imul($,Ve)|0,S=S+Math.imul(ee,Ke)|0,R=R+Math.imul(ee,Ve)|0,T=T+Math.imul(pe,Ge)|0,S=S+Math.imul(pe,Ze)|0,S=S+Math.imul(q,Ge)|0,R=R+Math.imul(q,Ze)|0,T=T+Math.imul(X,We)|0,S=S+Math.imul(X,Ye)|0,S=S+Math.imul(ne,We)|0,R=R+Math.imul(ne,Ye)|0;var tu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(tu>>>26)|0,tu&=67108863,T=Math.imul(xe,Fe),S=Math.imul(xe,He),S=S+Math.imul(ye,Fe)|0,R=Math.imul(ye,He),T=T+Math.imul(ge,je)|0,S=S+Math.imul(ge,ze)|0,S=S+Math.imul(ve,je)|0,R=R+Math.imul(ve,ze)|0,T=T+Math.imul(ue,Ke)|0,S=S+Math.imul(ue,Ve)|0,S=S+Math.imul(le,Ke)|0,R=R+Math.imul(le,Ve)|0,T=T+Math.imul($,Ge)|0,S=S+Math.imul($,Ze)|0,S=S+Math.imul(ee,Ge)|0,R=R+Math.imul(ee,Ze)|0,T=T+Math.imul(pe,We)|0,S=S+Math.imul(pe,Ye)|0,S=S+Math.imul(q,We)|0,R=R+Math.imul(q,Ye)|0,T=T+Math.imul(X,$e)|0,S=S+Math.imul(X,Xe)|0,S=S+Math.imul(ne,$e)|0,R=R+Math.imul(ne,Xe)|0;var ru=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(ru>>>26)|0,ru&=67108863,T=Math.imul(be,Fe),S=Math.imul(be,He),S=S+Math.imul(_e,Fe)|0,R=Math.imul(_e,He),T=T+Math.imul(xe,je)|0,S=S+Math.imul(xe,ze)|0,S=S+Math.imul(ye,je)|0,R=R+Math.imul(ye,ze)|0,T=T+Math.imul(ge,Ke)|0,S=S+Math.imul(ge,Ve)|0,S=S+Math.imul(ve,Ke)|0,R=R+Math.imul(ve,Ve)|0,T=T+Math.imul(ue,Ge)|0,S=S+Math.imul(ue,Ze)|0,S=S+Math.imul(le,Ge)|0,R=R+Math.imul(le,Ze)|0,T=T+Math.imul($,We)|0,S=S+Math.imul($,Ye)|0,S=S+Math.imul(ee,We)|0,R=R+Math.imul(ee,Ye)|0,T=T+Math.imul(pe,$e)|0,S=S+Math.imul(pe,Xe)|0,S=S+Math.imul(q,$e)|0,R=R+Math.imul(q,Xe)|0,T=T+Math.imul(X,Je)|0,S=S+Math.imul(X,Qe)|0,S=S+Math.imul(ne,Je)|0,R=R+Math.imul(ne,Qe)|0;var iu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(iu>>>26)|0,iu&=67108863,T=Math.imul(Me,Fe),S=Math.imul(Me,He),S=S+Math.imul(ke,Fe)|0,R=Math.imul(ke,He),T=T+Math.imul(be,je)|0,S=S+Math.imul(be,ze)|0,S=S+Math.imul(_e,je)|0,R=R+Math.imul(_e,ze)|0,T=T+Math.imul(xe,Ke)|0,S=S+Math.imul(xe,Ve)|0,S=S+Math.imul(ye,Ke)|0,R=R+Math.imul(ye,Ve)|0,T=T+Math.imul(ge,Ge)|0,S=S+Math.imul(ge,Ze)|0,S=S+Math.imul(ve,Ge)|0,R=R+Math.imul(ve,Ze)|0,T=T+Math.imul(ue,We)|0,S=S+Math.imul(ue,Ye)|0,S=S+Math.imul(le,We)|0,R=R+Math.imul(le,Ye)|0,T=T+Math.imul($,$e)|0,S=S+Math.imul($,Xe)|0,S=S+Math.imul(ee,$e)|0,R=R+Math.imul(ee,Xe)|0,T=T+Math.imul(pe,Je)|0,S=S+Math.imul(pe,Qe)|0,S=S+Math.imul(q,Je)|0,R=R+Math.imul(q,Qe)|0,T=T+Math.imul(X,et)|0,S=S+Math.imul(X,tt)|0,S=S+Math.imul(ne,et)|0,R=R+Math.imul(ne,tt)|0;var nu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(nu>>>26)|0,nu&=67108863,T=Math.imul(Ce,Fe),S=Math.imul(Ce,He),S=S+Math.imul(Le,Fe)|0,R=Math.imul(Le,He),T=T+Math.imul(Me,je)|0,S=S+Math.imul(Me,ze)|0,S=S+Math.imul(ke,je)|0,R=R+Math.imul(ke,ze)|0,T=T+Math.imul(be,Ke)|0,S=S+Math.imul(be,Ve)|0,S=S+Math.imul(_e,Ke)|0,R=R+Math.imul(_e,Ve)|0,T=T+Math.imul(xe,Ge)|0,S=S+Math.imul(xe,Ze)|0,S=S+Math.imul(ye,Ge)|0,R=R+Math.imul(ye,Ze)|0,T=T+Math.imul(ge,We)|0,S=S+Math.imul(ge,Ye)|0,S=S+Math.imul(ve,We)|0,R=R+Math.imul(ve,Ye)|0,T=T+Math.imul(ue,$e)|0,S=S+Math.imul(ue,Xe)|0,S=S+Math.imul(le,$e)|0,R=R+Math.imul(le,Xe)|0,T=T+Math.imul($,Je)|0,S=S+Math.imul($,Qe)|0,S=S+Math.imul(ee,Je)|0,R=R+Math.imul(ee,Qe)|0,T=T+Math.imul(pe,et)|0,S=S+Math.imul(pe,tt)|0,S=S+Math.imul(q,et)|0,R=R+Math.imul(q,tt)|0,T=T+Math.imul(X,rt)|0,S=S+Math.imul(X,it)|0,S=S+Math.imul(ne,rt)|0,R=R+Math.imul(ne,it)|0;var ou=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(ou>>>26)|0,ou&=67108863,T=Math.imul(qe,Fe),S=Math.imul(qe,He),S=S+Math.imul(Ue,Fe)|0,R=Math.imul(Ue,He),T=T+Math.imul(Ce,je)|0,S=S+Math.imul(Ce,ze)|0,S=S+Math.imul(Le,je)|0,R=R+Math.imul(Le,ze)|0,T=T+Math.imul(Me,Ke)|0,S=S+Math.imul(Me,Ve)|0,S=S+Math.imul(ke,Ke)|0,R=R+Math.imul(ke,Ve)|0,T=T+Math.imul(be,Ge)|0,S=S+Math.imul(be,Ze)|0,S=S+Math.imul(_e,Ge)|0,R=R+Math.imul(_e,Ze)|0,T=T+Math.imul(xe,We)|0,S=S+Math.imul(xe,Ye)|0,S=S+Math.imul(ye,We)|0,R=R+Math.imul(ye,Ye)|0,T=T+Math.imul(ge,$e)|0,S=S+Math.imul(ge,Xe)|0,S=S+Math.imul(ve,$e)|0,R=R+Math.imul(ve,Xe)|0,T=T+Math.imul(ue,Je)|0,S=S+Math.imul(ue,Qe)|0,S=S+Math.imul(le,Je)|0,R=R+Math.imul(le,Qe)|0,T=T+Math.imul($,et)|0,S=S+Math.imul($,tt)|0,S=S+Math.imul(ee,et)|0,R=R+Math.imul(ee,tt)|0,T=T+Math.imul(pe,rt)|0,S=S+Math.imul(pe,it)|0,S=S+Math.imul(q,rt)|0,R=R+Math.imul(q,it)|0,T=T+Math.imul(X,Jt)|0,S=S+Math.imul(X,Qt)|0,S=S+Math.imul(ne,Jt)|0,R=R+Math.imul(ne,Qt)|0;var au=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(au>>>26)|0,au&=67108863,T=Math.imul(qe,je),S=Math.imul(qe,ze),S=S+Math.imul(Ue,je)|0,R=Math.imul(Ue,ze),T=T+Math.imul(Ce,Ke)|0,S=S+Math.imul(Ce,Ve)|0,S=S+Math.imul(Le,Ke)|0,R=R+Math.imul(Le,Ve)|0,T=T+Math.imul(Me,Ge)|0,S=S+Math.imul(Me,Ze)|0,S=S+Math.imul(ke,Ge)|0,R=R+Math.imul(ke,Ze)|0,T=T+Math.imul(be,We)|0,S=S+Math.imul(be,Ye)|0,S=S+Math.imul(_e,We)|0,R=R+Math.imul(_e,Ye)|0,T=T+Math.imul(xe,$e)|0,S=S+Math.imul(xe,Xe)|0,S=S+Math.imul(ye,$e)|0,R=R+Math.imul(ye,Xe)|0,T=T+Math.imul(ge,Je)|0,S=S+Math.imul(ge,Qe)|0,S=S+Math.imul(ve,Je)|0,R=R+Math.imul(ve,Qe)|0,T=T+Math.imul(ue,et)|0,S=S+Math.imul(ue,tt)|0,S=S+Math.imul(le,et)|0,R=R+Math.imul(le,tt)|0,T=T+Math.imul($,rt)|0,S=S+Math.imul($,it)|0,S=S+Math.imul(ee,rt)|0,R=R+Math.imul(ee,it)|0,T=T+Math.imul(pe,Jt)|0,S=S+Math.imul(pe,Qt)|0,S=S+Math.imul(q,Jt)|0,R=R+Math.imul(q,Qt)|0;var su=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(su>>>26)|0,su&=67108863,T=Math.imul(qe,Ke),S=Math.imul(qe,Ve),S=S+Math.imul(Ue,Ke)|0,R=Math.imul(Ue,Ve),T=T+Math.imul(Ce,Ge)|0,S=S+Math.imul(Ce,Ze)|0,S=S+Math.imul(Le,Ge)|0,R=R+Math.imul(Le,Ze)|0,T=T+Math.imul(Me,We)|0,S=S+Math.imul(Me,Ye)|0,S=S+Math.imul(ke,We)|0,R=R+Math.imul(ke,Ye)|0,T=T+Math.imul(be,$e)|0,S=S+Math.imul(be,Xe)|0,S=S+Math.imul(_e,$e)|0,R=R+Math.imul(_e,Xe)|0,T=T+Math.imul(xe,Je)|0,S=S+Math.imul(xe,Qe)|0,S=S+Math.imul(ye,Je)|0,R=R+Math.imul(ye,Qe)|0,T=T+Math.imul(ge,et)|0,S=S+Math.imul(ge,tt)|0,S=S+Math.imul(ve,et)|0,R=R+Math.imul(ve,tt)|0,T=T+Math.imul(ue,rt)|0,S=S+Math.imul(ue,it)|0,S=S+Math.imul(le,rt)|0,R=R+Math.imul(le,it)|0,T=T+Math.imul($,Jt)|0,S=S+Math.imul($,Qt)|0,S=S+Math.imul(ee,Jt)|0,R=R+Math.imul(ee,Qt)|0;var uu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(uu>>>26)|0,uu&=67108863,T=Math.imul(qe,Ge),S=Math.imul(qe,Ze),S=S+Math.imul(Ue,Ge)|0,R=Math.imul(Ue,Ze),T=T+Math.imul(Ce,We)|0,S=S+Math.imul(Ce,Ye)|0,S=S+Math.imul(Le,We)|0,R=R+Math.imul(Le,Ye)|0,T=T+Math.imul(Me,$e)|0,S=S+Math.imul(Me,Xe)|0,S=S+Math.imul(ke,$e)|0,R=R+Math.imul(ke,Xe)|0,T=T+Math.imul(be,Je)|0,S=S+Math.imul(be,Qe)|0,S=S+Math.imul(_e,Je)|0,R=R+Math.imul(_e,Qe)|0,T=T+Math.imul(xe,et)|0,S=S+Math.imul(xe,tt)|0,S=S+Math.imul(ye,et)|0,R=R+Math.imul(ye,tt)|0,T=T+Math.imul(ge,rt)|0,S=S+Math.imul(ge,it)|0,S=S+Math.imul(ve,rt)|0,R=R+Math.imul(ve,it)|0,T=T+Math.imul(ue,Jt)|0,S=S+Math.imul(ue,Qt)|0,S=S+Math.imul(le,Jt)|0,R=R+Math.imul(le,Qt)|0;var fu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(fu>>>26)|0,fu&=67108863,T=Math.imul(qe,We),S=Math.imul(qe,Ye),S=S+Math.imul(Ue,We)|0,R=Math.imul(Ue,Ye),T=T+Math.imul(Ce,$e)|0,S=S+Math.imul(Ce,Xe)|0,S=S+Math.imul(Le,$e)|0,R=R+Math.imul(Le,Xe)|0,T=T+Math.imul(Me,Je)|0,S=S+Math.imul(Me,Qe)|0,S=S+Math.imul(ke,Je)|0,R=R+Math.imul(ke,Qe)|0,T=T+Math.imul(be,et)|0,S=S+Math.imul(be,tt)|0,S=S+Math.imul(_e,et)|0,R=R+Math.imul(_e,tt)|0,T=T+Math.imul(xe,rt)|0,S=S+Math.imul(xe,it)|0,S=S+Math.imul(ye,rt)|0,R=R+Math.imul(ye,it)|0,T=T+Math.imul(ge,Jt)|0,S=S+Math.imul(ge,Qt)|0,S=S+Math.imul(ve,Jt)|0,R=R+Math.imul(ve,Qt)|0;var cu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(cu>>>26)|0,cu&=67108863,T=Math.imul(qe,$e),S=Math.imul(qe,Xe),S=S+Math.imul(Ue,$e)|0,R=Math.imul(Ue,Xe),T=T+Math.imul(Ce,Je)|0,S=S+Math.imul(Ce,Qe)|0,S=S+Math.imul(Le,Je)|0,R=R+Math.imul(Le,Qe)|0,T=T+Math.imul(Me,et)|0,S=S+Math.imul(Me,tt)|0,S=S+Math.imul(ke,et)|0,R=R+Math.imul(ke,tt)|0,T=T+Math.imul(be,rt)|0,S=S+Math.imul(be,it)|0,S=S+Math.imul(_e,rt)|0,R=R+Math.imul(_e,it)|0,T=T+Math.imul(xe,Jt)|0,S=S+Math.imul(xe,Qt)|0,S=S+Math.imul(ye,Jt)|0,R=R+Math.imul(ye,Qt)|0;var lu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(lu>>>26)|0,lu&=67108863,T=Math.imul(qe,Je),S=Math.imul(qe,Qe),S=S+Math.imul(Ue,Je)|0,R=Math.imul(Ue,Qe),T=T+Math.imul(Ce,et)|0,S=S+Math.imul(Ce,tt)|0,S=S+Math.imul(Le,et)|0,R=R+Math.imul(Le,tt)|0,T=T+Math.imul(Me,rt)|0,S=S+Math.imul(Me,it)|0,S=S+Math.imul(ke,rt)|0,R=R+Math.imul(ke,it)|0,T=T+Math.imul(be,Jt)|0,S=S+Math.imul(be,Qt)|0,S=S+Math.imul(_e,Jt)|0,R=R+Math.imul(_e,Qt)|0;var hu=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(hu>>>26)|0,hu&=67108863,T=Math.imul(qe,et),S=Math.imul(qe,tt),S=S+Math.imul(Ue,et)|0,R=Math.imul(Ue,tt),T=T+Math.imul(Ce,rt)|0,S=S+Math.imul(Ce,it)|0,S=S+Math.imul(Le,rt)|0,R=R+Math.imul(Le,it)|0,T=T+Math.imul(Me,Jt)|0,S=S+Math.imul(Me,Qt)|0,S=S+Math.imul(ke,Jt)|0,R=R+Math.imul(ke,Qt)|0;var N5=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(N5>>>26)|0,N5&=67108863,T=Math.imul(qe,rt),S=Math.imul(qe,it),S=S+Math.imul(Ue,rt)|0,R=Math.imul(Ue,it),T=T+Math.imul(Ce,Jt)|0,S=S+Math.imul(Ce,Qt)|0,S=S+Math.imul(Le,Jt)|0,R=R+Math.imul(Le,Qt)|0;var C5=(I+T|0)+((S&8191)<<13)|0;I=(R+(S>>>13)|0)+(C5>>>26)|0,C5&=67108863,T=Math.imul(qe,Jt),S=Math.imul(qe,Qt),S=S+Math.imul(Ue,Jt)|0,R=Math.imul(Ue,Qt);var D5=(I+T|0)+((S&8191)<<13)|0;return I=(R+(S>>>13)|0)+(D5>>>26)|0,D5&=67108863,p[0]=Xs,p[1]=Js,p[2]=Qs,p[3]=eu,p[4]=tu,p[5]=ru,p[6]=iu,p[7]=nu,p[8]=ou,p[9]=au,p[10]=su,p[11]=uu,p[12]=fu,p[13]=cu,p[14]=lu,p[15]=hu,p[16]=N5,p[17]=C5,p[18]=D5,I!==0&&(p[19]=I,_.length++),_};Math.imul||(L=D);function U(y,f,d){d.negative=f.negative^y.negative,d.length=y.length+f.length;for(var _=0,x=0,b=0;b<d.length-1;b++){var p=x;x=0;for(var I=_&67108863,T=Math.min(b,f.length-1),S=Math.max(0,b-y.length+1);S<=T;S++){var R=b-S,Y=y.words[R]|0,X=f.words[S]|0,ne=Y*X,ce=ne&67108863;p=p+(ne/67108864|0)|0,ce=ce+I|0,I=ce&67108863,p=p+(ce>>>26)|0,x+=p>>>26,p&=67108863}d.words[b]=I,_=p,p=x}return _!==0?d.words[b]=_:d.length--,d._strip()}function K(y,f,d){return U(y,f,d)}n.prototype.mulTo=function(f,d){var _,x=this.length+f.length;return this.length===10&&f.length===10?_=L(this,f,d):x<63?_=D(this,f,d):x<1024?_=U(this,f,d):_=K(this,f,d),_};function N(y,f){this.x=y,this.y=f}N.prototype.makeRBT=function(f){for(var d=new Array(f),_=n.prototype._countBits(f)-1,x=0;x<f;x++)d[x]=this.revBin(x,_,f);return d},N.prototype.revBin=function(f,d,_){if(f===0||f===_-1)return f;for(var x=0,b=0;b<d;b++)x|=(f&1)<<d-b-1,f>>=1;return x},N.prototype.permute=function(f,d,_,x,b,p){for(var I=0;I<p;I++)x[I]=d[f[I]],b[I]=_[f[I]]},N.prototype.transform=function(f,d,_,x,b,p){this.permute(p,f,d,_,x,b);for(var I=1;I<b;I<<=1)for(var T=I<<1,S=Math.cos(2*Math.PI/T),R=Math.sin(2*Math.PI/T),Y=0;Y<b;Y+=T)for(var X=S,ne=R,ce=0;ce<I;ce++){var pe=_[Y+ce],q=x[Y+ce],W=_[Y+ce+I],$=x[Y+ce+I],ee=X*W-ne*$;$=X*$+ne*W,W=ee,_[Y+ce]=pe+W,x[Y+ce]=q+$,_[Y+ce+I]=pe-W,x[Y+ce+I]=q-$,ce!==T&&(ee=S*X-R*ne,ne=S*ne+R*X,X=ee)}},N.prototype.guessLen13b=function(f,d){var _=Math.max(d,f)|1,x=_&1,b=0;for(_=_/2|0;_;_=_>>>1)b++;return 1<<b+1+x},N.prototype.conjugate=function(f,d,_){if(!(_<=1))for(var x=0;x<_/2;x++){var b=f[x];f[x]=f[_-x-1],f[_-x-1]=b,b=d[x],d[x]=-d[_-x-1],d[_-x-1]=-b}},N.prototype.normalize13b=function(f,d){for(var _=0,x=0;x<d/2;x++){var b=Math.round(f[2*x+1]/d)*8192+Math.round(f[2*x]/d)+_;f[x]=b&67108863,b<67108864?_=0:_=b/67108864|0}return f},N.prototype.convert13b=function(f,d,_,x){for(var b=0,p=0;p<d;p++)b=b+(f[p]|0),_[2*p]=b&8191,b=b>>>13,_[2*p+1]=b&8191,b=b>>>13;for(p=2*d;p<x;++p)_[p]=0;r(b===0),r((b&-8192)===0)},N.prototype.stub=function(f){for(var d=new Array(f),_=0;_<f;_++)d[_]=0;return d},N.prototype.mulp=function(f,d,_){var x=2*this.guessLen13b(f.length,d.length),b=this.makeRBT(x),p=this.stub(x),I=new Array(x),T=new Array(x),S=new Array(x),R=new Array(x),Y=new Array(x),X=new Array(x),ne=_.words;ne.length=x,this.convert13b(f.words,f.length,I,x),this.convert13b(d.words,d.length,R,x),this.transform(I,p,T,S,x,b),this.transform(R,p,Y,X,x,b);for(var ce=0;ce<x;ce++){var pe=T[ce]*Y[ce]-S[ce]*X[ce];S[ce]=T[ce]*X[ce]+S[ce]*Y[ce],T[ce]=pe}return this.conjugate(T,S,x),this.transform(T,S,ne,p,x,b),this.conjugate(ne,p,x),this.normalize13b(ne,x),_.negative=f.negative^d.negative,_.length=f.length+d.length,_._strip()},n.prototype.mul=function(f){var d=new n(null);return d.words=new Array(this.length+f.length),this.mulTo(f,d)},n.prototype.mulf=function(f){var d=new n(null);return d.words=new Array(this.length+f.length),K(this,f,d)},n.prototype.imul=function(f){return this.clone().mulTo(f,this)},n.prototype.imuln=function(f){var d=f<0;d&&(f=-f),r(typeof f=="number"),r(f<67108864);for(var _=0,x=0;x<this.length;x++){var b=(this.words[x]|0)*f,p=(b&67108863)+(_&67108863);_>>=26,_+=b/67108864|0,_+=p>>>26,this.words[x]=p&67108863}return _!==0&&(this.words[x]=_,this.length++),this.length=f===0?1:this.length,d?this.ineg():this},n.prototype.muln=function(f){return this.clone().imuln(f)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(f){var d=M(f);if(d.length===0)return new n(1);for(var _=this,x=0;x<d.length&&d[x]===0;x++,_=_.sqr());if(++x<d.length)for(var b=_.sqr();x<d.length;x++,b=b.sqr())d[x]!==0&&(_=_.mul(b));return _},n.prototype.iushln=function(f){r(typeof f=="number"&&f>=0);var d=f%26,_=(f-d)/26,x=67108863>>>26-d<<26-d,b;if(d!==0){var p=0;for(b=0;b<this.length;b++){var I=this.words[b]&x,T=(this.words[b]|0)-I<<d;this.words[b]=T|p,p=I>>>26-d}p&&(this.words[b]=p,this.length++)}if(_!==0){for(b=this.length-1;b>=0;b--)this.words[b+_]=this.words[b];for(b=0;b<_;b++)this.words[b]=0;this.length+=_}return this._strip()},n.prototype.ishln=function(f){return r(this.negative===0),this.iushln(f)},n.prototype.iushrn=function(f,d,_){r(typeof f=="number"&&f>=0);var x;d?x=(d-d%26)/26:x=0;var b=f%26,p=Math.min((f-b)/26,this.length),I=67108863^67108863>>>b<<b,T=_;if(x-=p,x=Math.max(0,x),T){for(var S=0;S<p;S++)T.words[S]=this.words[S];T.length=p}if(p!==0)if(this.length>p)for(this.length-=p,S=0;S<this.length;S++)this.words[S]=this.words[S+p];else this.words[0]=0,this.length=1;var R=0;for(S=this.length-1;S>=0&&(R!==0||S>=x);S--){var Y=this.words[S]|0;this.words[S]=R<<26-b|Y>>>b,R=Y&I}return T&&R!==0&&(T.words[T.length++]=R),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},n.prototype.ishrn=function(f,d,_){return r(this.negative===0),this.iushrn(f,d,_)},n.prototype.shln=function(f){return this.clone().ishln(f)},n.prototype.ushln=function(f){return this.clone().iushln(f)},n.prototype.shrn=function(f){return this.clone().ishrn(f)},n.prototype.ushrn=function(f){return this.clone().iushrn(f)},n.prototype.testn=function(f){r(typeof f=="number"&&f>=0);var d=f%26,_=(f-d)/26,x=1<<d;if(this.length<=_)return!1;var b=this.words[_];return!!(b&x)},n.prototype.imaskn=function(f){r(typeof f=="number"&&f>=0);var d=f%26,_=(f-d)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=_)return this;if(d!==0&&_++,this.length=Math.min(_,this.length),d!==0){var x=67108863^67108863>>>d<<d;this.words[this.length-1]&=x}return this.length===0&&(this.words[0]=0,this.length=1),this._strip()},n.prototype.maskn=function(f){return this.clone().imaskn(f)},n.prototype.iaddn=function(f){return r(typeof f=="number"),r(f<67108864),f<0?this.isubn(-f):this.negative!==0?this.length===1&&(this.words[0]|0)<=f?(this.words[0]=f-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(f),this.negative=1,this):this._iaddn(f)},n.prototype._iaddn=function(f){this.words[0]+=f;for(var d=0;d<this.length&&this.words[d]>=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},n.prototype.isubn=function(f){if(r(typeof f=="number"),r(f<67108864),f<0)return this.iaddn(-f);if(this.negative!==0)return this.negative=0,this.iaddn(f),this.negative=1,this;if(this.words[0]-=f,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d<this.length&&this.words[d]<0;d++)this.words[d]+=67108864,this.words[d+1]-=1;return this._strip()},n.prototype.addn=function(f){return this.clone().iaddn(f)},n.prototype.subn=function(f){return this.clone().isubn(f)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(f,d,_){var x=f.length+_,b;this._expand(x);var p,I=0;for(b=0;b<f.length;b++){p=(this.words[b+_]|0)+I;var T=(f.words[b]|0)*d;p-=T&67108863,I=(p>>26)-(T/67108864|0),this.words[b+_]=p&67108863}for(;b<this.length-_;b++)p=(this.words[b+_]|0)+I,I=p>>26,this.words[b+_]=p&67108863;if(I===0)return this._strip();for(r(I===-1),I=0,b=0;b<this.length;b++)p=-(this.words[b]|0)+I,I=p>>26,this.words[b]=p&67108863;return this.negative=1,this._strip()},n.prototype._wordDiv=function(f,d){var _=this.length-f.length,x=this.clone(),b=f,p=b.words[b.length-1]|0,I=this._countBits(p);_=26-I,_!==0&&(b=b.ushln(_),x.iushln(_),p=b.words[b.length-1]|0);var T=x.length-b.length,S;if(d!=="mod"){S=new n(null),S.length=T+1,S.words=new Array(S.length);for(var R=0;R<S.length;R++)S.words[R]=0}var Y=x.clone()._ishlnsubmul(b,1,T);Y.negative===0&&(x=Y,S&&(S.words[T]=1));for(var X=T-1;X>=0;X--){var ne=(x.words[b.length+X]|0)*67108864+(x.words[b.length+X-1]|0);for(ne=Math.min(ne/p|0,67108863),x._ishlnsubmul(b,ne,X);x.negative!==0;)ne--,x.negative=0,x._ishlnsubmul(b,1,X),x.isZero()||(x.negative^=1);S&&(S.words[X]=ne)}return S&&S._strip(),x._strip(),d!=="div"&&_!==0&&x.iushrn(_),{div:S||null,mod:x}},n.prototype.divmod=function(f,d,_){if(r(!f.isZero()),this.isZero())return{div:new n(0),mod:new n(0)};var x,b,p;return this.negative!==0&&f.negative===0?(p=this.neg().divmod(f,d),d!=="mod"&&(x=p.div.neg()),d!=="div"&&(b=p.mod.neg(),_&&b.negative!==0&&b.iadd(f)),{div:x,mod:b}):this.negative===0&&f.negative!==0?(p=this.divmod(f.neg(),d),d!=="mod"&&(x=p.div.neg()),{div:x,mod:p.mod}):(this.negative&f.negative)!==0?(p=this.neg().divmod(f.neg(),d),d!=="div"&&(b=p.mod.neg(),_&&b.negative!==0&&b.isub(f)),{div:p.div,mod:b}):f.length>this.length||this.cmp(f)<0?{div:new n(0),mod:this}:f.length===1?d==="div"?{div:this.divn(f.words[0]),mod:null}:d==="mod"?{div:null,mod:new n(this.modrn(f.words[0]))}:{div:this.divn(f.words[0]),mod:new n(this.modrn(f.words[0]))}:this._wordDiv(f,d)},n.prototype.div=function(f){return this.divmod(f,"div",!1).div},n.prototype.mod=function(f){return this.divmod(f,"mod",!1).mod},n.prototype.umod=function(f){return this.divmod(f,"mod",!0).mod},n.prototype.divRound=function(f){var d=this.divmod(f);if(d.mod.isZero())return d.div;var _=d.div.negative!==0?d.mod.isub(f):d.mod,x=f.ushrn(1),b=f.andln(1),p=_.cmp(x);return p<0||b===1&&p===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},n.prototype.modrn=function(f){var d=f<0;d&&(f=-f),r(f<=67108863);for(var _=(1<<26)%f,x=0,b=this.length-1;b>=0;b--)x=(_*x+(this.words[b]|0))%f;return d?-x:x},n.prototype.modn=function(f){return this.modrn(f)},n.prototype.idivn=function(f){var d=f<0;d&&(f=-f),r(f<=67108863);for(var _=0,x=this.length-1;x>=0;x--){var b=(this.words[x]|0)+_*67108864;this.words[x]=b/f|0,_=b%f}return this._strip(),d?this.ineg():this},n.prototype.divn=function(f){return this.clone().idivn(f)},n.prototype.egcd=function(f){r(f.negative===0),r(!f.isZero());var d=this,_=f.clone();d.negative!==0?d=d.umod(f):d=d.clone();for(var x=new n(1),b=new n(0),p=new n(0),I=new n(1),T=0;d.isEven()&&_.isEven();)d.iushrn(1),_.iushrn(1),++T;for(var S=_.clone(),R=d.clone();!d.isZero();){for(var Y=0,X=1;(d.words[0]&X)===0&&Y<26;++Y,X<<=1);if(Y>0)for(d.iushrn(Y);Y-- >0;)(x.isOdd()||b.isOdd())&&(x.iadd(S),b.isub(R)),x.iushrn(1),b.iushrn(1);for(var ne=0,ce=1;(_.words[0]&ce)===0&&ne<26;++ne,ce<<=1);if(ne>0)for(_.iushrn(ne);ne-- >0;)(p.isOdd()||I.isOdd())&&(p.iadd(S),I.isub(R)),p.iushrn(1),I.iushrn(1);d.cmp(_)>=0?(d.isub(_),x.isub(p),b.isub(I)):(_.isub(d),p.isub(x),I.isub(b))}return{a:p,b:I,gcd:_.iushln(T)}},n.prototype._invmp=function(f){r(f.negative===0),r(!f.isZero());var d=this,_=f.clone();d.negative!==0?d=d.umod(f):d=d.clone();for(var x=new n(1),b=new n(0),p=_.clone();d.cmpn(1)>0&&_.cmpn(1)>0;){for(var I=0,T=1;(d.words[0]&T)===0&&I<26;++I,T<<=1);if(I>0)for(d.iushrn(I);I-- >0;)x.isOdd()&&x.iadd(p),x.iushrn(1);for(var S=0,R=1;(_.words[0]&R)===0&&S<26;++S,R<<=1);if(S>0)for(_.iushrn(S);S-- >0;)b.isOdd()&&b.iadd(p),b.iushrn(1);d.cmp(_)>=0?(d.isub(_),x.isub(b)):(_.isub(d),b.isub(x))}var Y;return d.cmpn(1)===0?Y=x:Y=b,Y.cmpn(0)<0&&Y.iadd(f),Y},n.prototype.gcd=function(f){if(this.isZero())return f.abs();if(f.isZero())return this.abs();var d=this.clone(),_=f.clone();d.negative=0,_.negative=0;for(var x=0;d.isEven()&&_.isEven();x++)d.iushrn(1),_.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;_.isEven();)_.iushrn(1);var b=d.cmp(_);if(b<0){var p=d;d=_,_=p}else if(b===0||_.cmpn(1)===0)break;d.isub(_)}while(!0);return _.iushln(x)},n.prototype.invm=function(f){return this.egcd(f).a.umod(f)},n.prototype.isEven=function(){return(this.words[0]&1)===0},n.prototype.isOdd=function(){return(this.words[0]&1)===1},n.prototype.andln=function(f){return this.words[0]&f},n.prototype.bincn=function(f){r(typeof f=="number");var d=f%26,_=(f-d)/26,x=1<<d;if(this.length<=_)return this._expand(_+1),this.words[_]|=x,this;for(var b=x,p=_;b!==0&&p<this.length;p++){var I=this.words[p]|0;I+=b,b=I>>>26,I&=67108863,this.words[p]=I}return b!==0&&(this.words[p]=b,this.length++),this},n.prototype.isZero=function(){return this.length===1&&this.words[0]===0},n.prototype.cmpn=function(f){var d=f<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var _;if(this.length>1)_=1;else{d&&(f=-f),r(f<=67108863,"Number is too big");var x=this.words[0]|0;_=x===f?0:x<f?-1:1}return this.negative!==0?-_|0:_},n.prototype.cmp=function(f){if(this.negative!==0&&f.negative===0)return-1;if(this.negative===0&&f.negative!==0)return 1;var d=this.ucmp(f);return this.negative!==0?-d|0:d},n.prototype.ucmp=function(f){if(this.length>f.length)return 1;if(this.length<f.length)return-1;for(var d=0,_=this.length-1;_>=0;_--){var x=this.words[_]|0,b=f.words[_]|0;if(x!==b){x<b?d=-1:x>b&&(d=1);break}}return d},n.prototype.gtn=function(f){return this.cmpn(f)===1},n.prototype.gt=function(f){return this.cmp(f)===1},n.prototype.gten=function(f){return this.cmpn(f)>=0},n.prototype.gte=function(f){return this.cmp(f)>=0},n.prototype.ltn=function(f){return this.cmpn(f)===-1},n.prototype.lt=function(f){return this.cmp(f)===-1},n.prototype.lten=function(f){return this.cmpn(f)<=0},n.prototype.lte=function(f){return this.cmp(f)<=0},n.prototype.eqn=function(f){return this.cmpn(f)===0},n.prototype.eq=function(f){return this.cmp(f)===0},n.red=function(f){return new g(f)},n.prototype.toRed=function(f){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),f.convertTo(this)._forceRed(f)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(f){return this.red=f,this},n.prototype.forceRed=function(f){return r(!this.red,"Already a number in reduction context"),this._forceRed(f)},n.prototype.redAdd=function(f){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,f)},n.prototype.redIAdd=function(f){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,f)},n.prototype.redSub=function(f){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,f)},n.prototype.redISub=function(f){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,f)},n.prototype.redShl=function(f){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,f)},n.prototype.redMul=function(f){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,f),this.red.mul(this,f)},n.prototype.redIMul=function(f){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,f),this.red.imul(this,f)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(f){return r(this.red&&!f.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,f)};var C={k256:null,p224:null,p192:null,p25519:null};function F(y,f){this.name=y,this.p=new n(f,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}F.prototype._tmp=function(){var f=new n(null);return f.words=new Array(Math.ceil(this.n/13)),f},F.prototype.ireduce=function(f){var d=f,_;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),_=d.bitLength();while(_>this.n);var x=_<this.n?-1:d.ucmp(this.p);return x===0?(d.words[0]=0,d.length=1):x>0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},F.prototype.split=function(f,d){f.iushrn(this.n,0,d)},F.prototype.imulK=function(f){return f.imul(this.k)};function H(){F.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(H,F),H.prototype.split=function(f,d){for(var _=4194303,x=Math.min(f.length,9),b=0;b<x;b++)d.words[b]=f.words[b];if(d.length=x,f.length<=9){f.words[0]=0,f.length=1;return}var p=f.words[9];for(d.words[d.length++]=p&_,b=10;b<f.length;b++){var I=f.words[b]|0;f.words[b-10]=(I&_)<<4|p>>>22,p=I}p>>>=22,f.words[b-10]=p,p===0&&f.length>10?f.length-=10:f.length-=9},H.prototype.imulK=function(f){f.words[f.length]=0,f.words[f.length+1]=0,f.length+=2;for(var d=0,_=0;_<f.length;_++){var x=f.words[_]|0;d+=x*977,f.words[_]=d&67108863,d=x*64+(d/67108864|0)}return f.words[f.length-1]===0&&(f.length--,f.words[f.length-1]===0&&f.length--),f};function z(){F.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i(z,F);function G(){F.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(G,F);function B(){F.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(B,F),B.prototype.imulK=function(f){for(var d=0,_=0;_<f.length;_++){var x=(f.words[_]|0)*19+d,b=x&67108863;x>>>=26,f.words[_]=b,d=x}return d!==0&&(f.words[f.length++]=d),f},n._prime=function(f){if(C[f])return C[f];var d;if(f==="k256")d=new H;else if(f==="p224")d=new z;else if(f==="p192")d=new G;else if(f==="p25519")d=new B;else throw new Error("Unknown prime "+f);return C[f]=d,d};function g(y){if(typeof y=="string"){var f=n._prime(y);this.m=f.p,this.prime=f}else r(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}g.prototype._verify1=function(f){r(f.negative===0,"red works only with positives"),r(f.red,"red works only with red numbers")},g.prototype._verify2=function(f,d){r((f.negative|d.negative)===0,"red works only with positives"),r(f.red&&f.red===d.red,"red works only with red numbers")},g.prototype.imod=function(f){return this.prime?this.prime.ireduce(f)._forceRed(this):(c(f,f.umod(this.m)._forceRed(this)),f)},g.prototype.neg=function(f){return f.isZero()?f.clone():this.m.sub(f)._forceRed(this)},g.prototype.add=function(f,d){this._verify2(f,d);var _=f.add(d);return _.cmp(this.m)>=0&&_.isub(this.m),_._forceRed(this)},g.prototype.iadd=function(f,d){this._verify2(f,d);var _=f.iadd(d);return _.cmp(this.m)>=0&&_.isub(this.m),_},g.prototype.sub=function(f,d){this._verify2(f,d);var _=f.sub(d);return _.cmpn(0)<0&&_.iadd(this.m),_._forceRed(this)},g.prototype.isub=function(f,d){this._verify2(f,d);var _=f.isub(d);return _.cmpn(0)<0&&_.iadd(this.m),_},g.prototype.shl=function(f,d){return this._verify1(f),this.imod(f.ushln(d))},g.prototype.imul=function(f,d){return this._verify2(f,d),this.imod(f.imul(d))},g.prototype.mul=function(f,d){return this._verify2(f,d),this.imod(f.mul(d))},g.prototype.isqr=function(f){return this.imul(f,f.clone())},g.prototype.sqr=function(f){return this.mul(f,f)},g.prototype.sqrt=function(f){if(f.isZero())return f.clone();var d=this.m.andln(3);if(r(d%2===1),d===3){var _=this.m.add(new n(1)).iushrn(2);return this.pow(f,_)}for(var x=this.m.subn(1),b=0;!x.isZero()&&x.andln(1)===0;)b++,x.iushrn(1);r(!x.isZero());var p=new n(1).toRed(this),I=p.redNeg(),T=this.m.subn(1).iushrn(1),S=this.m.bitLength();for(S=new n(2*S*S).toRed(this);this.pow(S,T).cmp(I)!==0;)S.redIAdd(I);for(var R=this.pow(S,x),Y=this.pow(f,x.addn(1).iushrn(1)),X=this.pow(f,x),ne=b;X.cmp(p)!==0;){for(var ce=X,pe=0;ce.cmp(p)!==0;pe++)ce=ce.redSqr();r(pe<ne);var q=this.pow(R,new n(1).iushln(ne-pe-1));Y=Y.redMul(q),R=q.redSqr(),X=X.redMul(R),ne=pe}return Y},g.prototype.invm=function(f){var d=f._invmp(this.m);return d.negative!==0?(d.negative=0,this.imod(d).redNeg()):this.imod(d)},g.prototype.pow=function(f,d){if(d.isZero())return new n(1).toRed(this);if(d.cmpn(1)===0)return f.clone();var _=4,x=new Array(1<<_);x[0]=new n(1).toRed(this),x[1]=f;for(var b=2;b<x.length;b++)x[b]=this.mul(x[b-1],f);var p=x[0],I=0,T=0,S=d.bitLength()%26;for(S===0&&(S=26),b=d.length-1;b>=0;b--){for(var R=d.words[b],Y=S-1;Y>=0;Y--){var X=R>>Y&1;if(p!==x[0]&&(p=this.sqr(p)),X===0&&I===0){T=0;continue}I<<=1,I|=X,T++,!(T!==_&&(b!==0||Y!==0))&&(p=this.mul(p,x[I]),T=0,I=0)}S=26}return p},g.prototype.convertTo=function(f){var d=f.umod(this.m);return d===f?d.clone():d},g.prototype.convertFrom=function(f){var d=f.clone();return d.red=null,d},n.mont=function(f){return new O(f)};function O(y){g.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(O,g),O.prototype.convertTo=function(f){return this.imod(f.ushln(this.shift))},O.prototype.convertFrom=function(f){var d=this.imod(f.mul(this.rinv));return d.red=null,d},O.prototype.imul=function(f,d){if(f.isZero()||d.isZero())return f.words[0]=0,f.length=1,f;var _=f.imul(d),x=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),b=_.isub(x).iushrn(this.shift),p=b;return b.cmp(this.m)>=0?p=b.isub(this.m):b.cmpn(0)<0&&(p=b.iadd(this.m)),p._forceRed(this)},O.prototype.mul=function(f,d){if(f.isZero()||d.isZero())return new n(0)._forceRed(this);var _=f.mul(d),x=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),b=_.isub(x).iushrn(this.shift),p=b;return b.cmp(this.m)>=0?p=b.isub(this.m):b.cmpn(0)<0&&(p=b.iadd(this.m)),p._forceRed(this)},O.prototype.invm=function(f){var d=this.imod(f._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(typeof Um>"u"||Um,FO)});var Fm=k((H1e,KO)=>{"use strict";v();var Mc=HO(),WY=mu(),YY=nt().Buffer;function jO(e){var t=e.modulus.byteLength(),r;do r=new Mc(WY(t));while(r.cmp(e.modulus)>=0||!r.umod(e.prime1)||!r.umod(e.prime2));return r}function $Y(e){var t=jO(e),r=t.toRed(Mc.mont(e.modulus)).redPow(new Mc(e.publicExponent)).fromRed();return{blinder:r,unblinder:t.invm(e.modulus)}}function zO(e,t){var r=$Y(t),i=t.modulus.byteLength(),n=new Mc(e).mul(r.blinder).umod(t.modulus),o=n.toRed(Mc.mont(t.prime1)),a=n.toRed(Mc.mont(t.prime2)),s=t.coefficient,u=t.prime1,c=t.prime2,l=o.redPow(t.exponent1).fromRed(),m=a.redPow(t.exponent2).fromRed(),w=l.isub(m).imul(s).umod(u).imul(c);return m.iadd(w).imul(r.unblinder).umod(t.modulus).toArrayLike(YY,"be",i)}zO.getr=jO;KO.exports=zO});var WO=k((z1e,ZO)=>{v();var XY=Nm(),Hm=mu(),JY=zh(),VO=Dm(),GO=Lm(),jm=Nn(),QY=qm(),e$=Fm(),Un=nt().Buffer;ZO.exports=function(t,r,i){var n;t.padding?n=t.padding:i?n=1:n=4;var o=XY(t),a;if(n===4)a=t$(o,r);else if(n===1)a=r$(o,r,i);else if(n===3){if(a=new jm(r),a.cmp(o.modulus)>=0)throw new Error("data too long for modulus")}else throw new Error("unknown padding");return i?e$(a,o):QY(a,o)};function t$(e,t){var r=e.modulus.byteLength(),i=t.length,n=JY("sha1").update(Un.alloc(0)).digest(),o=n.length,a=2*o;if(i>r-a-2)throw new Error("message too long");var s=Un.alloc(r-i-a-2),u=r-o-1,c=Hm(o),l=GO(Un.concat([n,s,Un.alloc(1,1),t],u),VO(c,u)),m=GO(c,VO(l,o));return new jm(Un.concat([Un.alloc(1),m,l],r))}function r$(e,t,r){var i=t.length,n=e.modulus.byteLength();if(i>n-11)throw new Error("message too long");var o;return r?o=Un.alloc(n-i-3,255):o=i$(n-i-3),new jm(Un.concat([Un.from([0,r?1:2]),o,Un.alloc(1),t],n))}function i$(e){for(var t=Un.allocUnsafe(e),r=0,i=Hm(e*2),n=0,o;r<e;)n===i.length&&(i=Hm(e*2),n=0),o=i[n++],o&&(t[r++]=o);return t}});var QO=k((V1e,JO)=>{v();var n$=Nm(),YO=Dm(),$O=Lm(),XO=Nn(),o$=Fm(),a$=zh(),s$=qm(),t0=nt().Buffer;JO.exports=function(t,r,i){var n;t.padding?n=t.padding:i?n=1:n=4;var o=n$(t),a=o.modulus.byteLength();if(r.length>a||new XO(r).cmp(o.modulus)>=0)throw new Error("decryption error");var s;i?s=s$(new XO(r),o):s=o$(r,o);var u=t0.alloc(a-s.length);if(s=t0.concat([u,s],a),n===4)return u$(o,s);if(n===1)return f$(o,s,i);if(n===3)return s;throw new Error("unknown padding")};function u$(e,t){var r=e.modulus.byteLength(),i=a$("sha1").update(t0.alloc(0)).digest(),n=i.length;if(t[0]!==0)throw new Error("decryption error");var o=t.slice(1,n+1),a=t.slice(n+1),s=$O(o,YO(a,n)),u=$O(a,YO(s,r-n-1));if(c$(i,u.slice(0,n)))throw new Error("decryption error");for(var c=n;u[c]===0;)c++;if(u[c++]!==1)throw new Error("decryption error");return u.slice(c)}function f$(e,t,r){for(var i=t.slice(0,2),n=2,o=0;t[n++]!==0;)if(n>=t.length){o++;break}var a=t.slice(2,n-1);if((i.toString("hex")!=="0002"&&!r||i.toString("hex")!=="0001"&&r)&&o++,a.length<8&&o++,o)throw new Error("decryption error");return t.slice(n)}function c$(e,t){e=t0.from(e),t=t0.from(t);var r=0,i=e.length;e.length!==t.length&&(r++,i=Math.min(e.length,t.length));for(var n=-1;++n<i;)r+=e[n]^t[n];return r}});var eI=k(Ku=>{v();Ku.publicEncrypt=WO();Ku.privateDecrypt=QO();Ku.privateEncrypt=function(t,r){return Ku.publicEncrypt(t,r,!0)};Ku.publicDecrypt=function(t,r){return Ku.privateDecrypt(t,r,!0)}});var cI=k(r0=>{"use strict";v();function tI(){throw new Error(`secure random number generation not supported by this browser
15
15
  use chrome, FireFox or Internet Explorer 11`)}var iI=nt(),rI=mu(),nI=iI.Buffer,oI=iI.kMaxLength,zm=globalThis.crypto||globalThis.msCrypto,aI=Math.pow(2,32)-1;function sI(e,t){if(typeof e!="number"||e!==e)throw new TypeError("offset must be a number");if(e>aI||e<0)throw new TypeError("offset must be a uint32");if(e>oI||e>t)throw new RangeError("offset out of range")}function uI(e,t,r){if(typeof e!="number"||e!==e)throw new TypeError("size must be a number");if(e>aI||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>oI)throw new RangeError("buffer too small")}zm&&zm.getRandomValues||!A.default.browser?(r0.randomFill=l$,r0.randomFillSync=h$):(r0.randomFill=tI,r0.randomFillSync=tI);function l$(e,t,r,i){if(!nI.isBuffer(e)&&!(e instanceof globalThis.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if(typeof t=="function")i=t,t=0,r=e.length;else if(typeof r=="function")i=r,r=e.length-t;else if(typeof i!="function")throw new TypeError('"cb" argument must be a function');return sI(t,e.length),uI(r,t,e.length),fI(e,t,r,i)}function fI(e,t,r,i){if(A.default.browser){var n=e.buffer,o=new Uint8Array(n,t,r);if(zm.getRandomValues(o),i){A.default.nextTick(function(){i(null,e)});return}return e}if(i){rI(r,function(s,u){if(s)return i(s);u.copy(e,t),i(null,e)});return}var a=rI(r);return a.copy(e,t),e}function h$(e,t,r){if(typeof t>"u"&&(t=0),!nI.isBuffer(e)&&!(e instanceof globalThis.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');return sI(t,e.length),r===void 0&&(r=e.length-t),uI(r,t,e.length),fI(e,t,r)}});var _r=k(ot=>{"use strict";v();ot.randomBytes=ot.rng=ot.pseudoRandomBytes=ot.prng=mu();ot.createHash=ot.Hash=zh();ot.createHmac=ot.Hmac=ax();var d$=fs(),p$=Object.keys(d$),g$=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(p$);ot.getHashes=function(){return g$};var lI=zv();ot.pbkdf2=lI.pbkdf2;ot.pbkdf2Sync=lI.pbkdf2Sync;var xo=RE();ot.Cipher=xo.Cipher;ot.createCipher=xo.createCipher;ot.Cipheriv=xo.Cipheriv;ot.createCipheriv=xo.createCipheriv;ot.Decipher=xo.Decipher;ot.createDecipher=xo.createDecipher;ot.Decipheriv=xo.Decipheriv;ot.createDecipheriv=xo.createDecipheriv;ot.getCiphers=xo.getCiphers;ot.listCiphers=xo.listCiphers;var i0=VE();ot.DiffieHellmanGroup=i0.DiffieHellmanGroup;ot.createDiffieHellmanGroup=i0.createDiffieHellmanGroup;ot.getDiffieHellman=i0.getDiffieHellman;ot.createDiffieHellman=i0.createDiffieHellman;ot.DiffieHellman=i0.DiffieHellman;var G2=fs();ot.createSign=G2.createSign;ot.Sign=G2.Sign;ot.createVerify=G2.createVerify;ot.Verify=G2.Verify;ot.createECDH=fs();var Z2=eI();ot.publicEncrypt=Z2.publicEncrypt;ot.privateEncrypt=Z2.privateEncrypt;ot.publicDecrypt=Z2.publicDecrypt;ot.privateDecrypt=Z2.privateDecrypt;var hI=cI();ot.randomFill=hI.randomFill;ot.randomFillSync=hI.randomFillSync;ot.createCredentials=function(){throw new Error(`sorry, createCredentials is not implemented yet
16
16
  we accept pull requests
17
- https://github.com/browserify/crypto-browserify`)};ot.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var ds=k((Q1e,dI)=>{"use strict";v();function Nc(){}Nc.getRandomBuffer=function(e){return A.default.browser?Nc.getRandomBufferBrowser(e):Nc.getRandomBufferNode(e)};Nc.getRandomBufferNode=function(e){var t=_r();return t.randomBytes(e)};Nc.getRandomBufferBrowser=function(e){if(!window.crypto&&!window.msCrypto)throw new Error("window.crypto not available");var t;if(window.crypto&&window.crypto.getRandomValues)t=window.crypto;else if(window.msCrypto&&window.msCrypto.getRandomValues)t=window.msCrypto;else throw new Error("window.crypto.getRandomValues not available");var r=new Uint8Array(e);t.getRandomValues(r);var i=h.Buffer.from(r);return i};dI.exports=Nc});var xt=k((tde,pI)=>{"use strict";v();var v$=ds(),Vt={};Vt.isArray=e=>Array.isArray(e);Vt.isNumber=e=>typeof e=="number";Vt.isObject=e=>e&&typeof e=="object";Vt.isString=e=>typeof e=="string";Vt.isUndefined=e=>typeof e>"u";Vt.isFunction=e=>typeof e=="function";Vt.isNull=e=>e===null;Vt.isDate=e=>e instanceof Date;Vt.extend=(e,t)=>Object.assign(e,t);Vt.noop=()=>{};Vt.every=(e,t)=>e.every(t||(r=>r));Vt.map=(e,t)=>Array.from(e).map(t||(r=>r));Vt.includes=(e,t)=>e.includes(t);Vt.each=(e,t)=>e.forEach(t);Vt.clone=e=>Object.assign({},e);Vt.pick=(e,t)=>{let r={};return t.forEach(i=>{typeof e[i]<"u"&&(r[i]=e[i])}),r};Vt.values=e=>Object.values(e);Vt.filter=(e,t)=>e.filter(t);Vt.reduce=(e,t,r)=>e.reduce(t,r);Vt.without=(e,t)=>e.filter(r=>r!==t);Vt.shuffle=e=>{let t=e.slice(0);for(let r=t.length-1;r>0;r--){let n=v$.getRandomBuffer(4).readUInt32BE(0)/4294967296,o=Math.floor(n*(r+1));[t[r],t[o]]=[t[o],t[r]]}return t};Vt.difference=(e,t)=>e.filter(r=>!t.includes(r));Vt.findIndex=(e,t)=>e.findIndex(t);Vt.some=(e,t)=>e.some(t);Vt.range=e=>[...Array(e).keys()];pI.exports=Vt});var vI=k((ide,gI)=>{"use strict";v();var W2=nt().Buffer;function m$(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var i=0;i<e.length;i++){var n=e.charAt(i),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=i}var a=e.length,s=e.charAt(0),u=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);function l(E){if((Array.isArray(E)||E instanceof Uint8Array)&&(E=W2.from(E)),!W2.isBuffer(E))throw new TypeError("Expected Buffer");if(E.length===0)return"";for(var P=0,M=0,D=0,L=E.length;D!==L&&E[D]===0;)D++,P++;for(var U=(L-D)*c+1>>>0,K=new Uint8Array(U);D!==L;){for(var N=E[D],C=0,F=U-1;(N!==0||C<M)&&F!==-1;F--,C++)N+=256*K[F]>>>0,K[F]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");M=C,D++}for(var H=U-M;H!==U&&K[H]===0;)H++;for(var z=s.repeat(P);H<U;++H)z+=e.charAt(K[H]);return z}function m(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return W2.alloc(0);for(var P=0,M=0,D=0;E[P]===s;)M++,P++;for(var L=(E.length-P)*u+1>>>0,U=new Uint8Array(L);P<E.length;){var K=E.charCodeAt(P);if(K>255)return;var N=t[K];if(N===255)return;for(var C=0,F=L-1;(N!==0||C<D)&&F!==-1;F--,C++)N+=a*U[F]>>>0,U[F]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");D=C,P++}for(var H=L-D;H!==L&&U[H]===0;)H++;var z=W2.allocUnsafe(M+(L-H));z.fill(0,0,M);for(var G=M;H!==L;)z[G++]=U[H++];return z}function w(E){var P=m(E);if(P)return P;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:m,decode:w}}gI.exports=m$});var Y2=k((ode,mI)=>{v();var y$=vI(),b$="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";mI.exports=y$(b$)});var Km=k((sde,yI)=>{"use strict";v();yI.exports="7.5.1"});var _I=k((fde,bI)=>{"use strict";v();var _$="https://docs.moneybutton.com/";bI.exports=[{name:"InvalidB58Char",message:"Invalid Base58 character: {0} in {1}"},{name:"InvalidB58Checksum",message:"Invalid Base58 checksum for {0}"},{name:"InvalidNetwork",message:"Invalid version for network: got {0}"},{name:"InvalidState",message:"Invalid state: {0}"},{name:"NotImplemented",message:"Function {0} was not implemented yet"},{name:"InvalidNetworkArgument",message:'Invalid network: must be "livenet" or "testnet", got {0}'},{name:"InvalidArgument",message:function(){return"Invalid Argument"+(arguments[0]?": "+arguments[0]:"")+(arguments[1]?" Documentation: "+_$+arguments[1]:"")}},{name:"AbstractMethodInvoked",message:"Abstract Method Invocation: {0}"},{name:"InvalidArgumentType",message:function(){return"Invalid Argument for "+arguments[2]+", expected "+arguments[1]+" but got "+typeof arguments[0]}},{name:"Unit",message:"Internal Error on Unit {0}",errors:[{name:"UnknownCode",message:"Unrecognized unit code: {0}"},{name:"InvalidRate",message:"Invalid exchange rate: {0}"}]},{name:"MerkleBlock",message:"Internal Error on MerkleBlock {0}",errors:[{name:"InvalidMerkleTree",message:"This MerkleBlock contain an invalid Merkle Tree"}]},{name:"Transaction",message:"Internal Error on Transaction {0}",errors:[{name:"Input",message:"Internal Error on Input {0}",errors:[{name:"MissingScript",message:"Need a script to create an input"},{name:"UnsupportedScript",message:"Unsupported input script type: {0}"},{name:"MissingPreviousOutput",message:"No previous output information."}]},{name:"NeedMoreInfo",message:"{0}"},{name:"InvalidSorting",message:"The sorting function provided did not return the change output as one of the array elements"},{name:"InvalidOutputAmountSum",message:"{0}"},{name:"MissingSignatures",message:"Some inputs have not been fully signed"},{name:"InvalidIndex",message:"Invalid index: {0} is not between 0, {1}"},{name:"UnableToVerifySignature",message:"Unable to verify signature: {0}"},{name:"DustOutputs",message:"Dust amount detected in one output"},{name:"InvalidSatoshis",message:"Output satoshis are invalid"},{name:"FeeError",message:"Internal Error on Fee {0}",errors:[{name:"TooSmall",message:"Fee is too small: {0}"},{name:"TooLarge",message:"Fee is too large: {0}"},{name:"Different",message:"Unspent value is different from specified fee: {0}"}]},{name:"ChangeAddressMissing",message:"Change address is missing"},{name:"BlockHeightTooHigh",message:"Block Height can be at most 2^32 -1"},{name:"NLockTimeOutOfRange",message:"Block Height can only be between 0 and 499 999 999"},{name:"LockTimeTooEarly",message:"Lock Time can't be earlier than UNIX date 500 000 000"}]},{name:"Script",message:"Internal Error on Script {0}",errors:[{name:"UnrecognizedAddress",message:"Expected argument {0} to be an address"},{name:"CantDeriveAddress",message:"Can't derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out."},{name:"InvalidBuffer",message:"Invalid script buffer: can't parse valid script from given buffer {0}"}]},{name:"HDPrivateKey",message:"Internal Error on HDPrivateKey {0}",errors:[{name:"InvalidDerivationArgument",message:"Invalid derivation argument {0}, expected string, or number and boolean"},{name:"InvalidEntropyArgument",message:"Invalid entropy: must be an hexa string or binary buffer, got {0}",errors:[{name:"TooMuchEntropy",message:'Invalid entropy: more than 512 bits is non standard, got "{0}"'},{name:"NotEnoughEntropy",message:'Invalid entropy: at least 128 bits needed, got "{0}"'}]},{name:"InvalidLength",message:"Invalid length for xprivkey string in {0}"},{name:"InvalidPath",message:"Invalid derivation path: {0}"},{name:"UnrecognizedArgument",message:'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'}]},{name:"HDPublicKey",message:"Internal Error on HDPublicKey {0}",errors:[{name:"ArgumentIsPrivateExtended",message:"Argument is an extended private key: {0}"},{name:"InvalidDerivationArgument",message:"Invalid derivation argument: got {0}"},{name:"InvalidLength",message:'Invalid length for xpubkey: got "{0}"'},{name:"InvalidPath",message:'Invalid derivation path, it should look like: "m/1/100", got "{0}"'},{name:"InvalidIndexCantDeriveHardened",message:"Invalid argument: creating a hardened path requires an HDPrivateKey"},{name:"MustSupplyArgument",message:"Must supply an argument to create a HDPublicKey"},{name:"UnrecognizedArgument",message:"Invalid argument for creation, must be string, json, buffer, or object"}]}]});var hn=k((lde,Gm)=>{"use strict";v();var Vm=xt();function w$(e,t){return e.replace("{0}",t[0]).replace("{1}",t[1]).replace("{2}",t[2])}var wI=function(e,t){var r=function(){if(Vm.isString(t.message))this.message=w$(t.message,arguments);else if(Vm.isFunction(t.message))this.message=t.message.apply(null,arguments);else throw new Error("Invalid error definition for "+t.name);this.stack=this.message+`
17
+ https://github.com/browserify/crypto-browserify`)};ot.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var ds=k((Q1e,dI)=>{"use strict";v();function Nc(){}Nc.getRandomBuffer=function(e){return A.default.browser?Nc.getRandomBufferBrowser(e):Nc.getRandomBufferNode(e)};Nc.getRandomBufferNode=function(e){var t=_r();return t.randomBytes(e)};Nc.getRandomBufferBrowser=function(e){if(!window.crypto&&!window.msCrypto)throw new Error("window.crypto not available");var t;if(window.crypto&&window.crypto.getRandomValues)t=window.crypto;else if(window.msCrypto&&window.msCrypto.getRandomValues)t=window.msCrypto;else throw new Error("window.crypto.getRandomValues not available");var r=new Uint8Array(e);t.getRandomValues(r);var i=h.Buffer.from(r);return i};dI.exports=Nc});var xt=k((tde,pI)=>{"use strict";v();var v$=ds(),Vt={};Vt.isArray=e=>Array.isArray(e);Vt.isNumber=e=>typeof e=="number";Vt.isObject=e=>e&&typeof e=="object";Vt.isString=e=>typeof e=="string";Vt.isUndefined=e=>typeof e>"u";Vt.isFunction=e=>typeof e=="function";Vt.isNull=e=>e===null;Vt.isDate=e=>e instanceof Date;Vt.extend=(e,t)=>Object.assign(e,t);Vt.noop=()=>{};Vt.every=(e,t)=>e.every(t||(r=>r));Vt.map=(e,t)=>Array.from(e).map(t||(r=>r));Vt.includes=(e,t)=>e.includes(t);Vt.each=(e,t)=>e.forEach(t);Vt.clone=e=>Object.assign({},e);Vt.pick=(e,t)=>{let r={};return t.forEach(i=>{typeof e[i]<"u"&&(r[i]=e[i])}),r};Vt.values=e=>Object.values(e);Vt.filter=(e,t)=>e.filter(t);Vt.reduce=(e,t,r)=>e.reduce(t,r);Vt.without=(e,t)=>e.filter(r=>r!==t);Vt.shuffle=e=>{let t=e.slice(0);for(let r=t.length-1;r>0;r--){let n=v$.getRandomBuffer(4).readUInt32BE(0)/4294967296,o=Math.floor(n*(r+1));[t[r],t[o]]=[t[o],t[r]]}return t};Vt.difference=(e,t)=>e.filter(r=>!t.includes(r));Vt.findIndex=(e,t)=>e.findIndex(t);Vt.some=(e,t)=>e.some(t);Vt.range=e=>[...Array(e).keys()];pI.exports=Vt});var vI=k((ide,gI)=>{"use strict";v();var W2=nt().Buffer;function m$(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var i=0;i<e.length;i++){var n=e.charAt(i),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=i}var a=e.length,s=e.charAt(0),u=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);function l(E){if((Array.isArray(E)||E instanceof Uint8Array)&&(E=W2.from(E)),!W2.isBuffer(E))throw new TypeError("Expected Buffer");if(E.length===0)return"";for(var P=0,M=0,D=0,L=E.length;D!==L&&E[D]===0;)D++,P++;for(var U=(L-D)*c+1>>>0,K=new Uint8Array(U);D!==L;){for(var N=E[D],C=0,F=U-1;(N!==0||C<M)&&F!==-1;F--,C++)N+=256*K[F]>>>0,K[F]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");M=C,D++}for(var H=U-M;H!==U&&K[H]===0;)H++;for(var z=s.repeat(P);H<U;++H)z+=e.charAt(K[H]);return z}function m(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return W2.alloc(0);for(var P=0,M=0,D=0;E[P]===s;)M++,P++;for(var L=(E.length-P)*u+1>>>0,U=new Uint8Array(L);P<E.length;){var K=E.charCodeAt(P);if(K>255)return;var N=t[K];if(N===255)return;for(var C=0,F=L-1;(N!==0||C<D)&&F!==-1;F--,C++)N+=a*U[F]>>>0,U[F]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");D=C,P++}for(var H=L-D;H!==L&&U[H]===0;)H++;var z=W2.allocUnsafe(M+(L-H));z.fill(0,0,M);for(var G=M;H!==L;)z[G++]=U[H++];return z}function w(E){var P=m(E);if(P)return P;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:m,decode:w}}gI.exports=m$});var Y2=k((ode,mI)=>{v();var y$=vI(),b$="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";mI.exports=y$(b$)});var Km=k((sde,yI)=>{"use strict";v();yI.exports="7.5.2"});var _I=k((fde,bI)=>{"use strict";v();var _$="https://docs.moneybutton.com/";bI.exports=[{name:"InvalidB58Char",message:"Invalid Base58 character: {0} in {1}"},{name:"InvalidB58Checksum",message:"Invalid Base58 checksum for {0}"},{name:"InvalidNetwork",message:"Invalid version for network: got {0}"},{name:"InvalidState",message:"Invalid state: {0}"},{name:"NotImplemented",message:"Function {0} was not implemented yet"},{name:"InvalidNetworkArgument",message:'Invalid network: must be "livenet" or "testnet", got {0}'},{name:"InvalidArgument",message:function(){return"Invalid Argument"+(arguments[0]?": "+arguments[0]:"")+(arguments[1]?" Documentation: "+_$+arguments[1]:"")}},{name:"AbstractMethodInvoked",message:"Abstract Method Invocation: {0}"},{name:"InvalidArgumentType",message:function(){return"Invalid Argument for "+arguments[2]+", expected "+arguments[1]+" but got "+typeof arguments[0]}},{name:"Unit",message:"Internal Error on Unit {0}",errors:[{name:"UnknownCode",message:"Unrecognized unit code: {0}"},{name:"InvalidRate",message:"Invalid exchange rate: {0}"}]},{name:"MerkleBlock",message:"Internal Error on MerkleBlock {0}",errors:[{name:"InvalidMerkleTree",message:"This MerkleBlock contain an invalid Merkle Tree"}]},{name:"Transaction",message:"Internal Error on Transaction {0}",errors:[{name:"Input",message:"Internal Error on Input {0}",errors:[{name:"MissingScript",message:"Need a script to create an input"},{name:"UnsupportedScript",message:"Unsupported input script type: {0}"},{name:"MissingPreviousOutput",message:"No previous output information."}]},{name:"NeedMoreInfo",message:"{0}"},{name:"InvalidSorting",message:"The sorting function provided did not return the change output as one of the array elements"},{name:"InvalidOutputAmountSum",message:"{0}"},{name:"MissingSignatures",message:"Some inputs have not been fully signed"},{name:"InvalidIndex",message:"Invalid index: {0} is not between 0, {1}"},{name:"UnableToVerifySignature",message:"Unable to verify signature: {0}"},{name:"DustOutputs",message:"Dust amount detected in one output"},{name:"InvalidSatoshis",message:"Output satoshis are invalid"},{name:"FeeError",message:"Internal Error on Fee {0}",errors:[{name:"TooSmall",message:"Fee is too small: {0}"},{name:"TooLarge",message:"Fee is too large: {0}"},{name:"Different",message:"Unspent value is different from specified fee: {0}"}]},{name:"ChangeAddressMissing",message:"Change address is missing"},{name:"BlockHeightTooHigh",message:"Block Height can be at most 2^32 -1"},{name:"NLockTimeOutOfRange",message:"Block Height can only be between 0 and 499 999 999"},{name:"LockTimeTooEarly",message:"Lock Time can't be earlier than UNIX date 500 000 000"}]},{name:"Script",message:"Internal Error on Script {0}",errors:[{name:"UnrecognizedAddress",message:"Expected argument {0} to be an address"},{name:"CantDeriveAddress",message:"Can't derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out."},{name:"InvalidBuffer",message:"Invalid script buffer: can't parse valid script from given buffer {0}"}]},{name:"HDPrivateKey",message:"Internal Error on HDPrivateKey {0}",errors:[{name:"InvalidDerivationArgument",message:"Invalid derivation argument {0}, expected string, or number and boolean"},{name:"InvalidEntropyArgument",message:"Invalid entropy: must be an hexa string or binary buffer, got {0}",errors:[{name:"TooMuchEntropy",message:'Invalid entropy: more than 512 bits is non standard, got "{0}"'},{name:"NotEnoughEntropy",message:'Invalid entropy: at least 128 bits needed, got "{0}"'}]},{name:"InvalidLength",message:"Invalid length for xprivkey string in {0}"},{name:"InvalidPath",message:"Invalid derivation path: {0}"},{name:"UnrecognizedArgument",message:'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'}]},{name:"HDPublicKey",message:"Internal Error on HDPublicKey {0}",errors:[{name:"ArgumentIsPrivateExtended",message:"Argument is an extended private key: {0}"},{name:"InvalidDerivationArgument",message:"Invalid derivation argument: got {0}"},{name:"InvalidLength",message:'Invalid length for xpubkey: got "{0}"'},{name:"InvalidPath",message:'Invalid derivation path, it should look like: "m/1/100", got "{0}"'},{name:"InvalidIndexCantDeriveHardened",message:"Invalid argument: creating a hardened path requires an HDPrivateKey"},{name:"MustSupplyArgument",message:"Must supply an argument to create a HDPublicKey"},{name:"UnrecognizedArgument",message:"Invalid argument for creation, must be string, json, buffer, or object"}]}]});var hn=k((lde,Gm)=>{"use strict";v();var Vm=xt();function w$(e,t){return e.replace("{0}",t[0]).replace("{1}",t[1]).replace("{2}",t[2])}var wI=function(e,t){var r=function(){if(Vm.isString(t.message))this.message=w$(t.message,arguments);else if(Vm.isFunction(t.message))this.message=t.message.apply(null,arguments);else throw new Error("Invalid error definition for "+t.name);this.stack=this.message+`
18
18
  `+new Error().stack};return r.prototype=Object.create(e.prototype),r.prototype.name=e.prototype.name+t.name,e[t.name]=r,t.errors&&SI(r,t.errors),r},SI=function(e,t){Vm.each(t,function(r){wI(e,r)})},S$=function(e,t){return SI(e,t),e},Cc={};Cc.Error=function(){this.message="Internal error",this.stack=this.message+`
19
19
  `+new Error().stack};Cc.Error.prototype=Object.create(Error.prototype);Cc.Error.prototype.name="bsv.Error";var x$=_I();S$(Cc.Error,x$);Gm.exports=Cc.Error;Gm.exports.extend=function(e){return wI(Cc.Error,e)}});var Bt=k((dde,xI)=>{"use strict";v();var n0=hn(),E$=xt();xI.exports={checkState:function(e,t){if(!e)throw new n0.InvalidState(t)},checkArgument:function(e,t,r,i){if(!e)throw new n0.InvalidArgument(t,r,i)},checkArgumentType:function(e,t,r){if(r=r||"(unknown name)",E$.isString(t)){if(t==="Buffer"){var i=Kt();if(!i.Buffer.isBuffer(e))throw new n0.InvalidArgumentType(e,t,r)}else if(typeof e!==t)throw new n0.InvalidArgumentType(e,t,r)}else if(!(e instanceof t))throw new n0.InvalidArgumentType(e,t.name,r)}}});var fr=k((gde,OI)=>{"use strict";v();var It=Nn(),Zm=Bt(),EI=xt(),$2=function(e){for(var t=h.Buffer.alloc(e.length),r=0;r<e.length;r++)t[r]=e[e.length-1-r];return t};It.Zero=new It(0);It.One=new It(1);It.Minus1=new It(-1);It.fromNumber=function(e){return Zm.checkArgument(EI.isNumber(e)),new It(e)};It.fromString=function(e,t){return Zm.checkArgument(EI.isString(e)),new It(e,t)};It.fromBuffer=function(e,t){typeof t<"u"&&t.endian==="little"&&(e=$2(e));var r=e.toString("hex"),i=new It(r,16);return i};It.fromSM=function(e,t){var r;if(e.length===0)return It.fromBuffer(h.Buffer.from([0]));var i="big";return t&&(i=t.endian),i==="little"&&(e=$2(e)),e[0]&128?(e[0]=e[0]&127,r=It.fromBuffer(e),r.neg().copy(r)):r=It.fromBuffer(e),r};It.prototype.toNumber=function(){return parseInt(this.toString(10),10)};It.prototype.toBuffer=function(e){var t,r;if(e&&e.size){r=this.toString(16,2);var i=r.length/2;t=h.Buffer.from(r,"hex"),i===e.size||(i>e.size?t=It.trim(t,i):i<e.size&&(t=It.pad(t,i,e.size)))}else r=this.toString(16,2),t=h.Buffer.from(r,"hex");return typeof e<"u"&&e.endian==="little"&&(t=$2(t)),t};It.prototype.toSMBigEndian=function(){var e;return this.cmp(It.Zero)===-1?(e=this.neg().toBuffer(),e[0]&128?e=h.Buffer.concat([h.Buffer.from([128]),e]):e[0]=e[0]|128):(e=this.toBuffer(),e[0]&128&&(e=h.Buffer.concat([h.Buffer.from([0]),e]))),e.length===1&e[0]===0&&(e=h.Buffer.from([])),e};It.prototype.toSM=function(e){var t=e?e.endian:"big",r=this.toSMBigEndian();return t==="little"&&(r=$2(r)),r};It.fromScriptNumBuffer=function(e,t,r){var i=r||4;if(Zm.checkArgument(e.length<=i,new Error("script number overflow")),t&&e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))throw new Error("non-minimally encoded script number");return It.fromSM(e,{endian:"little"})};It.prototype.toScriptNumBuffer=function(){return this.toSM({endian:"little"})};It.trim=function(e,t){return e.slice(t-e.length,e.length)};It.pad=function(e,t,r){for(var i=h.Buffer.alloc(r),n=0;n<e.length;n++)i[i.length-1-n]=e[e.length-1-n];for(n=0;n<r-t;n++)i[n]=0;return i};It.prototype.toHex=function(...e){return this.toBuffer(...e).toString("hex")};It.fromHex=function(e,...t){return It.fromBuffer(h.Buffer.from(e,"hex"),...t)};OI.exports=It});function Wm(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function ps(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new RangeError(`${r}expected integer >= 0, got ${e}`)}}function Eo(e,t,r=""){let i=Wm(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let a=r&&`"${r}" `,s=o?` of length ${t}`:"",u=i?`length=${n}`:`type=${typeof e}`,c=a+"expected Uint8Array"+s+", got "+u;throw i?new RangeError(c):new TypeError(c)}return e}function X2(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ps(e.outputLen),ps(e.blockLen),e.outputLen<1)throw new Error('"outputLen" must be >= 1');if(e.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Dc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function J2(e,t){Eo(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function Sa(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Q2(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Fn(e,t){return e<<32-t|e>>>t}function ep(e){if(Eo(e),AI)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=O$[e[r]];return t}function II(e){if(e>=wa._0&&e<=wa._9)return e-wa._0;if(e>=wa.A&&e<=wa.F)return e-(wa.A-10);if(e>=wa.a&&e<=wa.f)return e-(wa.a-10)}function Ym(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(AI)try{return Uint8Array.fromHex(e)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let a=II(e.charCodeAt(o)),s=II(e.charCodeAt(o+1));if(a===void 0||s===void 0){let u=e[o]+e[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}i[n]=a*16+s}return i}function xa(e){if(typeof e!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function PI(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];Eo(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function Vu(e,t={}){let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=n=>e(n),Object.assign(r,t),Object.freeze(r)}function o0(e=32){ps(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var AI,O$,wa,Gu,gs=Xr(()=>{v();AI=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",O$=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));wa={_0:48,_9:57,A:65,F:70,a:97,f:102};Gu=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])})});function TI(e,t,r){return e&t^~e&r}function kI(e,t,r){return e&t^e&r^t&r}var a0,Ea,Oa,Qr,ei,RI=Xr(()=>{v();gs();a0=class{constructor(t,r,i,n){Z(this,"blockLen");Z(this,"outputLen");Z(this,"canXOF",!1);Z(this,"padOffset");Z(this,"isLE");Z(this,"buffer");Z(this,"view");Z(this,"finished",!1);Z(this,"length",0);Z(this,"pos",0);Z(this,"destroyed",!1);this.blockLen=t,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(t),this.view=Q2(this.buffer)}update(t){Dc(this),Eo(t);let{view:r,buffer:i,blockLen:n}=this,o=t.length;for(let a=0;a<o;){let s=Math.min(n-this.pos,o-a);if(s===n){let u=Q2(t);for(;n<=o-a;a+=n)this.process(u,a);continue}i.set(t.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Dc(this),J2(t,this),this.finished=!0;let{buffer:r,view:i,blockLen:n,isLE:o}=this,{pos:a}=this;r[a++]=128,Sa(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(i,0),a=0);for(let m=a;m<n;m++)r[m]=0;i.setBigUint64(n-8,BigInt(this.length*8),o),this.process(i,0);let s=Q2(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let m=0;m<c;m++)s.setUint32(4*m,l[m],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let i=t.slice(0,r);return this.destroy(),i}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:i,length:n,finished:o,destroyed:a,pos:s}=this;return t.destroyed=a,t.finished=o,t.length=n,t.pos=s,n%r&&t.buffer.set(i),t}clone(){return this._cloneInto()}},Ea=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oa=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Qr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ei=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function I$(e,t=!1){return t?{h:Number(e&tp),l:Number(e>>BI&tp)}:{h:Number(e>>BI&tp)|0,l:Number(e&tp)|0}}function MI(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:a,l:s}=I$(e[o],t);[i[o],n[o]]=[a,s]}return[i,n]}function Oo(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/2**32|0)|0,l:n|0}}var tp,BI,$m,Xm,Zu,Wu,s0,u0,NI,CI,DI,LI,qI,UI,FI=Xr(()=>{v();tp=BigInt(4294967295),BI=BigInt(32);$m=(e,t,r)=>e>>>r,Xm=(e,t,r)=>e<<32-r|t>>>r,Zu=(e,t,r)=>e>>>r|t<<32-r,Wu=(e,t,r)=>e<<32-r|t>>>r,s0=(e,t,r)=>e<<64-r|t>>>r-32,u0=(e,t,r)=>e>>>r-32|t<<64-r;NI=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),CI=(e,t,r,i)=>t+r+i+(e/2**32|0)|0,DI=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),LI=(e,t,r,i,n)=>t+r+i+n+(e/2**32|0)|0,qI=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),UI=(e,t,r,i,n,o)=>t+r+i+n+o+(e/2**32|0)|0});var Jm={};Q1(Jm,{_SHA224:()=>np,_SHA256:()=>ip,_SHA384:()=>ap,_SHA512:()=>op,_SHA512_224:()=>sp,_SHA512_256:()=>up,sha224:()=>R$,sha256:()=>bs,sha384:()=>M$,sha512:()=>B$,sha512_224:()=>C$,sha512_256:()=>N$});var P$,vs,rp,ip,np,HI,T$,k$,ms,ys,Lc,op,ap,hi,di,sp,up,bs,R$,B$,M$,N$,C$,fp=Xr(()=>{v();RI();FI();gs();P$=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),vs=new Uint32Array(64),rp=class extends a0{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:i,D:n,E:o,F:a,G:s,H:u}=this;return[t,r,i,n,o,a,s,u]}set(t,r,i,n,o,a,s,u){this.A=t|0,this.B=r|0,this.C=i|0,this.D=n|0,this.E=o|0,this.F=a|0,this.G=s|0,this.H=u|0}process(t,r){for(let m=0;m<16;m++,r+=4)vs[m]=t.getUint32(r,!1);for(let m=16;m<64;m++){let w=vs[m-15],E=vs[m-2],P=Fn(w,7)^Fn(w,18)^w>>>3,M=Fn(E,17)^Fn(E,19)^E>>>10;vs[m]=M+vs[m-7]+P+vs[m-16]|0}let{A:i,B:n,C:o,D:a,E:s,F:u,G:c,H:l}=this;for(let m=0;m<64;m++){let w=Fn(s,6)^Fn(s,11)^Fn(s,25),E=l+w+TI(s,u,c)+P$[m]+vs[m]|0,M=(Fn(i,2)^Fn(i,13)^Fn(i,22))+kI(i,n,o)|0;l=c,c=u,u=s,s=a+E|0,a=o,o=n,n=i,i=E+M|0}i=i+this.A|0,n=n+this.B|0,o=o+this.C|0,a=a+this.D|0,s=s+this.E|0,u=u+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(i,n,o,a,s,u,c,l)}roundClean(){Sa(vs)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Sa(this.buffer)}},ip=class extends rp{constructor(){super(32);Z(this,"A",Ea[0]|0);Z(this,"B",Ea[1]|0);Z(this,"C",Ea[2]|0);Z(this,"D",Ea[3]|0);Z(this,"E",Ea[4]|0);Z(this,"F",Ea[5]|0);Z(this,"G",Ea[6]|0);Z(this,"H",Ea[7]|0)}},np=class extends rp{constructor(){super(28);Z(this,"A",Oa[0]|0);Z(this,"B",Oa[1]|0);Z(this,"C",Oa[2]|0);Z(this,"D",Oa[3]|0);Z(this,"E",Oa[4]|0);Z(this,"F",Oa[5]|0);Z(this,"G",Oa[6]|0);Z(this,"H",Oa[7]|0)}},HI=MI(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),T$=HI[0],k$=HI[1],ms=new Uint32Array(80),ys=new Uint32Array(80),Lc=class extends a0{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:i,Bl:n,Ch:o,Cl:a,Dh:s,Dl:u,Eh:c,El:l,Fh:m,Fl:w,Gh:E,Gl:P,Hh:M,Hl:D}=this;return[t,r,i,n,o,a,s,u,c,l,m,w,E,P,M,D]}set(t,r,i,n,o,a,s,u,c,l,m,w,E,P,M,D){this.Ah=t|0,this.Al=r|0,this.Bh=i|0,this.Bl=n|0,this.Ch=o|0,this.Cl=a|0,this.Dh=s|0,this.Dl=u|0,this.Eh=c|0,this.El=l|0,this.Fh=m|0,this.Fl=w|0,this.Gh=E|0,this.Gl=P|0,this.Hh=M|0,this.Hl=D|0}process(t,r){for(let K=0;K<16;K++,r+=4)ms[K]=t.getUint32(r),ys[K]=t.getUint32(r+=4);for(let K=16;K<80;K++){let N=ms[K-15]|0,C=ys[K-15]|0,F=Zu(N,C,1)^Zu(N,C,8)^$m(N,C,7),H=Wu(N,C,1)^Wu(N,C,8)^Xm(N,C,7),z=ms[K-2]|0,G=ys[K-2]|0,B=Zu(z,G,19)^s0(z,G,61)^$m(z,G,6),g=Wu(z,G,19)^u0(z,G,61)^Xm(z,G,6),O=DI(H,g,ys[K-7],ys[K-16]),y=LI(O,F,B,ms[K-7],ms[K-16]);ms[K]=y|0,ys[K]=O|0}let{Ah:i,Al:n,Bh:o,Bl:a,Ch:s,Cl:u,Dh:c,Dl:l,Eh:m,El:w,Fh:E,Fl:P,Gh:M,Gl:D,Hh:L,Hl:U}=this;for(let K=0;K<80;K++){let N=Zu(m,w,14)^Zu(m,w,18)^s0(m,w,41),C=Wu(m,w,14)^Wu(m,w,18)^u0(m,w,41),F=m&E^~m&M,H=w&P^~w&D,z=qI(U,C,H,k$[K],ys[K]),G=UI(z,L,N,F,T$[K],ms[K]),B=z|0,g=Zu(i,n,28)^s0(i,n,34)^s0(i,n,39),O=Wu(i,n,28)^u0(i,n,34)^u0(i,n,39),y=i&o^i&s^o&s,f=n&a^n&u^a&u;L=M|0,U=D|0,M=E|0,D=P|0,E=m|0,P=w|0,{h:m,l:w}=Oo(c|0,l|0,G|0,B|0),c=s|0,l=u|0,s=o|0,u=a|0,o=i|0,a=n|0;let d=NI(B,O,f);i=CI(d,G,g,y),n=d|0}({h:i,l:n}=Oo(this.Ah|0,this.Al|0,i|0,n|0)),{h:o,l:a}=Oo(this.Bh|0,this.Bl|0,o|0,a|0),{h:s,l:u}=Oo(this.Ch|0,this.Cl|0,s|0,u|0),{h:c,l}=Oo(this.Dh|0,this.Dl|0,c|0,l|0),{h:m,l:w}=Oo(this.Eh|0,this.El|0,m|0,w|0),{h:E,l:P}=Oo(this.Fh|0,this.Fl|0,E|0,P|0),{h:M,l:D}=Oo(this.Gh|0,this.Gl|0,M|0,D|0),{h:L,l:U}=Oo(this.Hh|0,this.Hl|0,L|0,U|0),this.set(i,n,o,a,s,u,c,l,m,w,E,P,M,D,L,U)}roundClean(){Sa(ms,ys)}destroy(){this.destroyed=!0,Sa(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},op=class extends Lc{constructor(){super(64);Z(this,"Ah",ei[0]|0);Z(this,"Al",ei[1]|0);Z(this,"Bh",ei[2]|0);Z(this,"Bl",ei[3]|0);Z(this,"Ch",ei[4]|0);Z(this,"Cl",ei[5]|0);Z(this,"Dh",ei[6]|0);Z(this,"Dl",ei[7]|0);Z(this,"Eh",ei[8]|0);Z(this,"El",ei[9]|0);Z(this,"Fh",ei[10]|0);Z(this,"Fl",ei[11]|0);Z(this,"Gh",ei[12]|0);Z(this,"Gl",ei[13]|0);Z(this,"Hh",ei[14]|0);Z(this,"Hl",ei[15]|0)}},ap=class extends Lc{constructor(){super(48);Z(this,"Ah",Qr[0]|0);Z(this,"Al",Qr[1]|0);Z(this,"Bh",Qr[2]|0);Z(this,"Bl",Qr[3]|0);Z(this,"Ch",Qr[4]|0);Z(this,"Cl",Qr[5]|0);Z(this,"Dh",Qr[6]|0);Z(this,"Dl",Qr[7]|0);Z(this,"Eh",Qr[8]|0);Z(this,"El",Qr[9]|0);Z(this,"Fh",Qr[10]|0);Z(this,"Fl",Qr[11]|0);Z(this,"Gh",Qr[12]|0);Z(this,"Gl",Qr[13]|0);Z(this,"Hh",Qr[14]|0);Z(this,"Hl",Qr[15]|0)}},hi=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),di=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),sp=class extends Lc{constructor(){super(28);Z(this,"Ah",hi[0]|0);Z(this,"Al",hi[1]|0);Z(this,"Bh",hi[2]|0);Z(this,"Bl",hi[3]|0);Z(this,"Ch",hi[4]|0);Z(this,"Cl",hi[5]|0);Z(this,"Dh",hi[6]|0);Z(this,"Dl",hi[7]|0);Z(this,"Eh",hi[8]|0);Z(this,"El",hi[9]|0);Z(this,"Fh",hi[10]|0);Z(this,"Fl",hi[11]|0);Z(this,"Gh",hi[12]|0);Z(this,"Gl",hi[13]|0);Z(this,"Hh",hi[14]|0);Z(this,"Hl",hi[15]|0)}},up=class extends Lc{constructor(){super(32);Z(this,"Ah",di[0]|0);Z(this,"Al",di[1]|0);Z(this,"Bh",di[2]|0);Z(this,"Bl",di[3]|0);Z(this,"Ch",di[4]|0);Z(this,"Cl",di[5]|0);Z(this,"Dh",di[6]|0);Z(this,"Dl",di[7]|0);Z(this,"Eh",di[8]|0);Z(this,"El",di[9]|0);Z(this,"Fh",di[10]|0);Z(this,"Fl",di[11]|0);Z(this,"Gh",di[12]|0);Z(this,"Gl",di[13]|0);Z(this,"Hh",di[14]|0);Z(this,"Hl",di[15]|0)}},bs=Vu(()=>new ip,Gu(1)),R$=Vu(()=>new np,Gu(4)),B$=Vu(()=>new op,Gu(3)),M$=Vu(()=>new ap,Gu(2)),N$=Vu(()=>new up,Gu(6)),C$=Vu(()=>new sp,Gu(5))});function $u(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new TypeError(r+"expected boolean, got type="+typeof e)}return e}function hp(e){if(typeof e=="bigint"){if(!cp(e))throw new RangeError("positive bigint expected, got "+e)}else ey(e);return e}function dn(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function f0(e){let t=hp(e).toString(16);return t.length&1?"0"+t:t}function jI(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?lp:BigInt("0x"+e)}function bi(e){return jI(ep(e))}function Uc(e){return jI(ep(pp(Eo(e)).reverse()))}function dp(e,t){if(ps(t),t===0)throw new RangeError("zero length");e=hp(e);let r=e.toString(16);if(r.length>t*2)throw new RangeError("number too large");return Ym(r.padStart(t*2,"0"))}function ty(e,t){return dp(e,t).reverse()}function pp(e){return Uint8Array.from(qt(e))}function Fc(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}function D$(e,t,r){return cp(e)&&cp(t)&&cp(r)&&t<=e&&e<r}function ry(e,t,r,i){if(!D$(t,r,i))throw new RangeError("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function Xu(e){if(e<lp)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>lp;e>>=Qm,t+=1);return t}function zI(e,t,r){if(ps(e,"hashLen"),ps(t,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let i=D=>new Uint8Array(D),n=Uint8Array.of(),o=Uint8Array.of(0),a=Uint8Array.of(1),s=1e3,u=i(e),c=i(e),l=0,m=()=>{u.fill(1),c.fill(0),l=0},w=(...D)=>r(c,kt(u,...D)),E=(D=n)=>{c=w(o,D),u=w(),D.length!==0&&(c=w(a,D),u=w())},P=()=>{if(l++>=s)throw new Error("drbg: tried max amount of iterations");let D=0,L=[];for(;D<t;){u=w();let U=u.slice();L.push(U),D+=u.length}return kt(...L)};return(D,L)=>{m(),E(D);let U;for(;(U=L(P()))===void 0;)E();return m(),U}}function pn(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function i(o,a,s){if(!s&&a!=="function"&&!Object.hasOwn(e,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=e[o];if(s&&u===void 0)return;let c=typeof u;if(c!==a||u===null)throw new TypeError(`param "${o}" is invalid: expected ${a}, got ${c}`)}let n=(o,a)=>Object.entries(o).forEach(([s,u])=>i(s,u,a));n(t,!1),n(r,!0)}var qt,ey,Ia,kt,qc,Yu,ki,lp,Qm,cp,Hc,Ju=Xr(()=>{v();gs();qt=(e,t,r)=>Eo(e,t,r),ey=ps,Ia=ep,kt=(...e)=>PI(...e),qc=e=>Ym(e),Yu=Wm,ki=e=>o0(e),lp=BigInt(0),Qm=BigInt(1);cp=e=>typeof e=="bigint"&&lp<=e;Hc=e=>(Qm<<BigInt(e))-Qm});function Ui(e,t){if(t<=ti)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=ti?r:t+r}function Fi(e,t,r){if(t<ti)throw new Error("pow2: expected non-negative exponent, got "+t);let i=e;for(;t-- >ti;)i*=i,i%=r;return i}function KI(e,t){if(e===ti)throw new Error("invert: expected non-zero number");if(t<=ti)throw new Error("invert: expected positive modulus, got "+t);let r=Ui(e,t),i=t,n=ti,o=wr,a=wr,s=ti;for(;r!==ti;){let c=i/r,l=i-r*c,m=n-a*c,w=o-s*c;i=r,r=l,n=a,o=s,a=m,s=w}if(i!==wr)throw new Error("invert: does not exist");return Ui(n,t)}function ny(e,t,r){let i=e;if(!i.eql(i.sqr(t),r))throw new Error("Cannot find square root")}function XI(e,t){let r=e,i=(r.ORDER+wr)/ZI,n=r.pow(t,i);return ny(r,n,t),n}function U$(e,t){let r=e,i=(r.ORDER-WI)/YI,n=r.mul(t,Qu),o=r.pow(n,i),a=r.mul(t,o),s=r.mul(r.mul(a,Qu),o),u=r.mul(a,r.sub(s,r.ONE));return ny(r,u,t),u}function F$(e){let t=jc(e),r=JI(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),a=(e+L$)/$I;return((s,u)=>{let c=s,l=c.pow(u,a),m=c.mul(l,i),w=c.mul(l,n),E=c.mul(l,o),P=c.eql(c.sqr(m),u),M=c.eql(c.sqr(w),u);l=c.cmov(l,m,P),m=c.cmov(E,w,M);let D=c.eql(c.sqr(m),u),L=c.cmov(l,m,D);return ny(c,L,u),L})}function JI(e){if(e<GI)throw new Error("sqrt is not defined for small field");let t=e-wr,r=0;for(;t%Qu===ti;)t/=Qu,r++;let i=Qu,n=jc(e);for(;iy(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return XI;let o=n.pow(i,t),a=(t+wr)/Qu;return function(u,c){let l=u;if(l.is0(c))return c;if(iy(l,c)!==1)throw new Error("Cannot find square root");let m=r,w=l.mul(l.ONE,o),E=l.pow(c,t),P=l.pow(c,a);for(;!l.eql(E,l.ONE);){if(l.is0(E))return l.ZERO;let M=1,D=l.sqr(E);for(;!l.eql(D,l.ONE);)if(M++,D=l.sqr(D),M===m)throw new Error("Cannot find square root");let L=wr<<BigInt(m-M-1),U=l.pow(w,L);m=M,w=l.sqr(U),E=l.mul(E,w),P=l.mul(P,U)}return P}}function H$(e){return e%ZI===GI?XI:e%YI===WI?U$:e%$I===q$?F$(e):JI(e)}function ef(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=j$.reduce((i,n)=>(i[n]="function",i),t);if(pn(e,r),dn(e.BYTES,"BYTES"),dn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=wr)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function z$(e,t,r){let i=e;if(r<ti)throw new Error("invalid exponent, negatives unsupported");if(r===ti)return i.ONE;if(r===wr)return t;let n=i.ONE,o=t;for(;r>ti;)r&wr&&(n=i.mul(n,o)),o=i.sqr(o),r>>=wr;return n}function tf(e,t,r=!1){let i=e,n=new Array(t.length).fill(r?i.ZERO:void 0),o=t.reduce((s,u,c)=>i.is0(u)?s:(n[c]=s,i.mul(s,u)),i.ONE),a=i.inv(o);return t.reduceRight((s,u,c)=>i.is0(u)?s:(n[c]=i.mul(s,n[c]),i.mul(s,u)),a),n}function iy(e,t){let r=e,i=(r.ORDER-wr)/Qu,n=r.pow(t,i),o=r.eql(n,r.ONE),a=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!a&&!s)throw new Error("invalid Legendre symbol result");return o?1:a?0:-1}function oy(e,t){return iy(e,t)!==-1}function K$(e,t){if(t!==void 0&&ey(t),e<=ti)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=Xu(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let i=t!==void 0?t:r,n=Math.ceil(i/8);return{nBitLength:i,nByteLength:n}}function jc(e,t={}){return new gp(e,t)}function QI(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=wr)throw new Error("field order must be greater than 1");let t=Xu(e-wr);return Math.ceil(t/8)}function c0(e){let t=QI(e);return t+Math.ceil(t/2)}function zc(e,t,r=!1){qt(e);let i=e.length,n=QI(t),o=Math.max(c0(t),16);if(i<o||i>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+i);let a=r?Uc(e):bi(e),s=Ui(a,t-wr)+wr;return r?ty(s,n):dp(s,n)}var ti,wr,Qu,GI,ZI,WI,L$,YI,q$,$I,j$,VI,gp,Kc=Xr(()=>{v();Ju();ti=BigInt(0),wr=BigInt(1),Qu=BigInt(2),GI=BigInt(3),ZI=BigInt(4),WI=BigInt(5),L$=BigInt(7),YI=BigInt(8),q$=BigInt(9),$I=BigInt(16);j$=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];VI=new WeakMap,gp=class{constructor(t,r={}){Z(this,"ORDER");Z(this,"BITS");Z(this,"BYTES");Z(this,"isLE");Z(this,"ZERO",ti);Z(this,"ONE",wr);Z(this,"_lengths");Z(this,"_mod");if(t<=wr)throw new Error("invalid field: expected ORDER > 1, got "+t);let i;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(i=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:n,nByteLength:o}=K$(t,i);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(t){return Ui(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return ti<=t&&t<this.ORDER}is0(t){return t===ti}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&wr)===wr}neg(t){return Ui(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return Ui(t*t,this.ORDER)}add(t,r){return Ui(t+r,this.ORDER)}sub(t,r){return Ui(t-r,this.ORDER)}mul(t,r){return Ui(t*r,this.ORDER)}pow(t,r){return z$(this,t,r)}div(t,r){return Ui(t*KI(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return KI(t,this.ORDER)}sqrt(t){let r=VI.get(this);return r||VI.set(this,r=H$(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?ty(t,this.BYTES):dp(t,this.BYTES)}fromBytes(t,r=!1){qt(t);let{_lengths:i,BYTES:n,isLE:o,ORDER:a,_mod:s}=this;if(i){if(t.length<1||!i.includes(t.length)||t.length>n)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+t.length);let c=new Uint8Array(n);c.set(t,o?0:c.length-t.length),t=c}if(t.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=o?Uc(t):bi(t);if(s&&(u=Ui(u,a)),!r&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(t){return tf(this,t)}cmov(t,r,i){return $u(i,"condition"),i?r:t}};Object.freeze(gp.prototype)});function iA(e){let t=e;if(typeof t!="function")throw new TypeError("Point must be a constructor");pn({Fp:t.Fp,Fn:t.Fn,fromAffine:t.fromAffine,fromBytes:t.fromBytes,fromHex:t.fromHex},{Fp:"object",Fn:"object",fromAffine:"function",fromBytes:"function",fromHex:"function"}),ef(t.Fp),ef(t.Fn)}function l0(e,t){let r=t.negate();return e?r:t}function fy(e,t){let r=tf(e.Fp,t.map(i=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function nA(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ay(e,t){nA(e,t);let r=Math.ceil(t/e)+1,i=2**(e-1),n=2**e,o=Hc(e),a=BigInt(e);return{windows:r,windowSize:i,mask:o,maxNumber:n,shiftBy:a}}function eA(e,t,r){let{windowSize:i,mask:n,maxNumber:o,shiftBy:a}=r,s=Number(e&n),u=e>>a;s>i&&(s-=o,u+=rf);let c=t*i,l=c+Math.abs(s)-1,m=s===0,w=s<0,E=t%2!==0;return{nextN:u,offset:l,isZero:m,isNeg:w,isNegF:E,offsetF:c}}function V$(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,i)=>{if(!(r instanceof t))throw new Error("invalid point at index "+i)})}function G$(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,i)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+i)})}function uy(e){return oA.get(e)||1}function tA(e){if(e!==Vc)throw new Error("invalid wNAF")}function aA(e,t,r,i){let n=t,o=e.ZERO,a=e.ZERO;for(;r>Vc||i>Vc;)r&rf&&(o=o.add(n)),i&rf&&(a=a.add(n)),n=n.double(),r>>=rf,i>>=rf;return{p1:o,p2:a}}function sA(e,t,r){let i=e.Fn;V$(t,e),G$(r,i);let n=t.length,o=r.length;if(n!==o)throw new Error("arrays of points and scalars must have equal length");let a=e.ZERO,s=Xu(BigInt(n)),u=1;s>12?u=s-3:s>4?u=s-2:s>0&&(u=2);let c=Hc(u),l=new Array(Number(c)+1).fill(a),m=Math.floor((i.BITS-1)/u)*u,w=a;for(let E=m;E>=0;E-=u){l.fill(a);for(let M=0;M<o;M++){let D=r[M],L=Number(D>>BigInt(E)&c);l[L]=l[L].add(t[M])}let P=a;for(let M=l.length-1,D=a;M>0;M--)D=D.add(l[M]),P=P.add(D);if(w=w.add(P),E!==0)for(let M=0;M<u;M++)w=w.double()}return w}function rA(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ef(t),t}else return jc(e,{isLE:r})}function uA(e,t,r={},i){if(i===void 0&&(i=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let u of["p","n","h"]){let c=t[u];if(!(typeof c=="bigint"&&c>Vc))throw new Error(`CURVE.${u} must be positive bigint`)}let n=rA(t.p,r.Fp,i),o=rA(t.n,r.Fn,i),s=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let u of s)if(!n.isValid(t[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:o}}function mp(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}var Vc,rf,sy,oA,vp,yp=Xr(()=>{v();Ju();Kc();Vc=BigInt(0),rf=BigInt(1);sy=new WeakMap,oA=new WeakMap;vp=class{constructor(t,r){Z(this,"BASE");Z(this,"ZERO");Z(this,"Fn");Z(this,"bits");this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,i=this.ZERO){let n=t;for(;r>Vc;)r&rf&&(i=i.add(n)),n=n.double(),r>>=rf;return i}precomputeWindow(t,r){let{windows:i,windowSize:n}=ay(r,this.bits),o=[],a=t,s=a;for(let u=0;u<i;u++){s=a,o.push(s);for(let c=1;c<n;c++)s=s.add(a),o.push(s);a=s.double()}return o}wNAF(t,r,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,a=ay(t,this.bits);for(let s=0;s<a.windows;s++){let{nextN:u,offset:c,isZero:l,isNeg:m,isNegF:w,offsetF:E}=eA(i,s,a);i=u,l?o=o.add(l0(w,r[E])):n=n.add(l0(m,r[c]))}return tA(i),{p:n,f:o}}wNAFUnsafe(t,r,i,n=this.ZERO){let o=ay(t,this.bits);for(let a=0;a<o.windows&&i!==Vc;a++){let{nextN:s,offset:u,isZero:c,isNeg:l}=eA(i,a,o);if(i=s,!c){let m=r[u];n=n.add(l?m.negate():m)}}return tA(i),n}getPrecomputes(t,r,i){let n=sy.get(r);return n||(n=this.precomputeWindow(r,t),t!==1&&(typeof i=="function"&&(n=i(n)),sy.set(r,n))),n}cached(t,r,i){let n=uy(t);return this.wNAF(n,this.getPrecomputes(n,t,i),r)}unsafe(t,r,i,n){let o=uy(t);return o===1?this._unsafeLadder(t,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,i),r,n)}createCache(t,r){nA(r,this.bits),oA.set(t,r),sy.delete(t)}hasCache(t){return uy(t)!==1}}});function fA(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error("wrong u32 integer:"+e);return e}function Z$(e){if(fA(e),e<=1)return 1;if(e>2147483648)throw new Error("nextPowerOfTwo overflow: result does not fit u32");return 1<<cy(e-1)+1>>>0}function cy(e){return fA(e),31-Math.clz32(e)}function cA(e,t,r,i,n){let o=e,a=r||((l,m)=>new Array(l).fill(m??o.ZERO)),s=l=>{if(Array.isArray(l))return!0;if(!ArrayBuffer.isView(l))return!1;let m=l;return typeof m.length=="number"&&typeof m.slice=="function"&&typeof m[Symbol.iterator]=="function"},u=(...l)=>{if(!l.length)return 0;for(let w of l)if(!s(w))throw new Error("poly: not polynomial: "+w);let m=l[0].length;for(let w=1;w<l.length;w++)if(l[w].length!==m)throw new Error(`poly: mismatched lengths ${m} vs ${l[w].length}`);if(n!==void 0&&m!==n)throw new Error(`poly: expected fixed length ${n}, got ${m}`);return m};function c(l,m,w=!1){let E=cy(m),P=w?t.brp(E):t.roots(E);for(let M=0;M<m;M++)if(o.eql(l,P[M]))return M;return-1}return{roots:t,create:a,length:n,extend:(l,m)=>{u(l);let w=a(m,o.ZERO);for(let E=0;E<Math.min(l.length,m);E++)w[E]=l[E];return w},degree:l=>{u(l);for(let m=l.length-1;m>=0;m--)if(!o.is0(l[m]))return m;return-1},add:(l,m)=>{let w=u(l,m),E=a(w);for(let P=0;P<w;P++)E[P]=o.add(l[P],m[P]);return E},sub:(l,m)=>{let w=u(l,m),E=a(w);for(let P=0;P<w;P++)E[P]=o.sub(l[P],m[P]);return E},dot:(l,m)=>{let w=u(l,m),E=a(w);for(let P=0;P<w;P++)E[P]=o.mul(l[P],m[P]);return E},mul:(l,m)=>{if(s(m)){let w=u(l,m);if(i){let E=i.direct(l,!1,!0),P=i.direct(m,!1,!0);for(let M=0;M<E.length;M++)E[M]=o.mul(E[M],P[M]);return i.inverse(E,!0,!1)}else{let E=a(w);for(let P=0;P<w;P++)for(let M=0;M<w;M++){let D=(P+M)%w;E[D]=o.add(E[D],o.mul(l[P],m[M]))}return E}}else{let w=a(u(l));for(let E=0;E<w.length;E++)w[E]=o.mul(l[E],m);return w}},convolve(l,m){let w=Z$(l.length+m.length-1);return this.mul(this.extend(l,w),this.extend(m,w))},shift(l,m){let w=a(u(l));w[0]=l[0];for(let E=1,P=o.ONE;E<l.length;E++)P=o.mul(P,m),w[E]=o.mul(l[E],P);return w},clone:l=>{u(l);let m=a(l.length);for(let w=0;w<l.length;w++)m[w]=l[w];return m},eval:(l,m)=>{u(l,m);let w=o.ZERO;for(let E=0;E<l.length;E++)w=o.add(w,o.mul(l[E],m[E]));return w},monomial:{basis:(l,m)=>{let w=a(m),E=o.ONE;for(let P=0;P<m;P++)w[P]=E,E=o.mul(E,l);return w},eval:(l,m)=>{u(l);let w=o.ZERO;for(let E=l.length-1;E>=0;E--)w=o.add(o.mul(w,m),l[E]);return w}},lagrange:{basis:(l,m,w=!1,E)=>{let P=cy(m),M=E||(w?t.brp(P):t.roots(P)),D=a(m),L=c(l,m,w);if(L!==-1)return D[L]=o.ONE,D;let U=o.pow(l,BigInt(m)),K=o.mul(o.sub(U,o.ONE),o.inv(BigInt(m))),N=a(m);for(let F=0;F<m;F++)N[F]=o.sub(l,M[F]);let C=o.invertBatch(N);for(let F=0;F<m;F++)D[F]=o.mul(K,o.mul(M[F],C[F]));return D},eval(l,m,w=!1){u(l);let E=c(m,l.length,w);if(E!==-1)return l[E];let P=this.basis(m,l.length,w),M=o.ZERO;for(let D=0;D<l.length;D++)o.is0(l[D])||(M=o.add(M,o.mul(l[D],P[D])));return M}},vanishing(l){u(l);let m=a(l.length+1,o.ZERO);m[0]=o.ONE;for(let w of l){let E=o.neg(w);for(let P=m.length-1;P>0;P--)m[P]=o.add(o.mul(m[P],E),m[P-1]);m[0]=o.mul(m[0],E)}return m}}}var lA=Xr(()=>{v()});function nf(e,t){if(dn(e),dn(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let i=t-1;i>=0;i--)r[i]=e&255,e>>>=8;return new Uint8Array(r)}function Y$(e,t){let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}function hA(e){if(!Yu(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?Fc(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function $$(e,t,r,i){qt(e),dn(r),t=hA(t),t.length>255&&(t=i(kt(Fc("H2C-OVERSIZE-DST-"),t)));let{outputLen:n,blockLen:o}=i,a=Math.ceil(r/n);if(r>65535||a>255)throw new Error("expand_message_xmd: invalid lenInBytes");let s=kt(t,nf(t.length,1)),u=new Uint8Array(o),c=nf(r,2),l=new Array(a),m=i(kt(u,e,c,nf(0,1),s));l[0]=i(kt(m,nf(1,1),s));for(let E=1;E<a;E++){let P=[Y$(m,l[E-1]),nf(E+1,1),s];l[E]=i(kt(...P))}return kt(...l).slice(0,r)}function X$(e,t,r,i,n){if(qt(e),dn(r),t=hA(t),t.length>255){let o=Math.ceil(2*i/8);t=n.create({dkLen:o}).update(Fc("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return n.create({dkLen:r}).update(e).update(nf(r,2)).update(t).update(nf(t.length,1)).digest()}function ly(e,t,r){pn(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:i,k:n,m:o,hash:a,expand:s,DST:u}=r;if(dn(a.outputLen,"valid hash"),qt(e),dn(t),t<1)throw new Error("hash_to_field: expected count >= 1");if(o<1)throw new Error("hash_to_field: expected m >= 1");let c=i.toString(2).length,l=Math.ceil((c+n)/8),m=t*o*l,w;if(s==="xmd")w=$$(e,u,m,a);else if(s==="xof")w=X$(e,u,m,n,a);else if(s==="_internal_pass")w=e;else throw new Error('expand must be "xmd" or "xof"');let E=new Array(t);for(let P=0;P<t;P++){let M=new Array(o);for(let D=0;D<o;D++){let L=l*(D+P*o),U=w.subarray(L,L+l);M[D]=Ui(W$(U),i)}E[P]=M}return E}function dA(e,t){let r=t.map(i=>Array.from(i).reverse());return(i,n)=>{let[o,a,s,u]=r.map(m=>m.reduce((w,E)=>e.add(e.mul(w,i),E))),[c,l]=tf(e,[a,u],!0);return i=e.mul(o,c),n=e.mul(n,e.mul(s,l)),{x:i,y:n}}}function pA(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");let i=s=>Object.freeze({...s,DST:Yu(s.DST)?pp(s.DST):s.DST,...s.encodeDST===void 0?{}:{encodeDST:Yu(s.encodeDST)?pp(s.encodeDST):s.encodeDST}}),n=i(r);function o(s){return e.fromAffine(t(s))}function a(s){let u=s.clearCofactor();return u.equals(e.ZERO)?e.ZERO:(u.assertValidity(),u)}return Object.freeze({get defaults(){return i(n)},Point:e,hashToCurve(s,u){let c=Object.assign({},n,u),l=ly(s,2,c),m=o(l[0]),w=o(l[1]);return a(m.add(w))},encodeToCurve(s,u){let c=n.encodeDST?{DST:n.encodeDST}:{},l=Object.assign({},n,c,u),m=ly(s,1,l),w=o(m[0]);return a(w)},mapToCurve(s){if(n.m===1){if(typeof s!="bigint")throw new Error("expected bigint (m=1)");return a(o([s]))}if(!Array.isArray(s))throw new Error("expected array of bigints");for(let u of s)if(typeof u!="bigint")throw new Error("expected array of bigints");return a(o(s))},hashToScalar(s,u){let c=e.Fn.ORDER,l=Object.assign({},n,{p:c,m:1,DST:J$},u);return ly(s,1,l)[0][0]}})}var W$,J$,gA=Xr(()=>{v();Ju();Kc();W$=bi;J$="HashToScalar-"});function hy(e){pn(e,{name:"string",hash:"function"},{hashToScalar:"function",validatePoint:"function",parsePublicKey:"function",adjustScalar:"function",adjustPoint:"function",challenge:"function",adjustNonces:"function",adjustSecret:"function",adjustPublic:"function",adjustGroupCommitmentShare:"function",adjustDKG:"function"}),iA(e.Point);let{Point:t}=e,r=e.Fn===void 0?t.Fn:e.Fn,i=e.hash,n=e.hashToScalar===void 0?(q,W={DST:new Uint8Array})=>{let $=i(kt(W.DST,q));return r.create(r.isLE?Uc($):bi($))}:e.hashToScalar,o=xa(e.H1!==void 0?e.H1:e.name+"rho"),a=xa(e.H2!==void 0?e.H2:e.name+"chal"),s=xa(e.H3!==void 0?e.H3:e.name+"nonce"),u=xa(e.H4!==void 0?e.H4:e.name+"msg"),c=xa(e.H5!==void 0?e.H5:e.name+"com"),l=xa(e.HDKG!==void 0?e.HDKG:e.name+"dkg"),m=xa(e.HID!==void 0?e.HID:e.name+"id"),w=q=>n(q,{DST:o}),E=q=>n(q,{DST:a}),P=q=>n(q,{DST:s}),M=q=>i(kt(u,q)),D=q=>i(kt(c,q)),L=q=>n(q,{DST:l}),U=q=>n(q,{DST:m}),K=(q=ki)=>{let W=zc(q(c0(r.ORDER)),r.ORDER,r.isLE);return r.isLE?Uc(W):bi(W)},N=q=>q.toBytes(),C=q=>{let W=t.fromBytes(q);return e.validatePoint&&e.validatePoint(W),W},F=(q,W)=>({identifier:q,hiding:N(t.BASE.multiply(r.fromBytes(W.hiding))),binding:N(t.BASE.multiply(r.fromBytes(W.binding)))}),H=e.adjustPoint===void 0?q=>q:e.adjustPoint,z=q=>{if(!r.isValid(q)||r.is0(q))throw new Error("Invalid identifier "+q);return q},G=q=>Ia(r.toBytes(z(q))),B=q=>{let W=z(r.fromBytes(qc(q)));if(G(W)!==q)throw new Error("expected canonical identifier hex");return W},g={encode:(q,W)=>{let $=kt(N(q),r.toBytes(W));return e.adjustTx&&($=e.adjustTx.encode($)),$},decode:q=>{e.adjustTx&&(q=e.adjustTx.decode(q));let W=C(q.subarray(0,-r.BYTES)),$=r.fromBytes(q.subarray(-r.BYTES));return{R:W,z:$}}},O=(q=ki)=>{let W=K(q);e.adjustScalar&&(W=e.adjustScalar(W));let $=t.BASE.multiply(W);return{scalar:W,point:$}},y="roots are unavailable in FROST polynomial mode",f={info:{G:r.ZERO,oddFactor:r.ZERO,powerOfTwo:0},roots(){throw new Error(y)},brp(){throw new Error(y)},inverse(){throw new Error(y)},omega(){throw new Error(y)},clear(){}},d=cA(r,f),_=(q,W)=>sA(t,q,W),x=(q,W)=>{if(!W.length)throw new Error("empty coefficients");return d.monomial.eval(W,q)},b=(q,W)=>{let $="invalid parameters";if(!q.some(le=>r.eql(le,W)))throw new Error($);let ee=new Set(q);if(ee.size!==q.length)throw new Error($);if(!ee.has(W))throw new Error($);let se=r.ONE,ue=r.ONE;for(let le of q)r.eql(le,W)||(se=r.mul(se,le),ue=r.mul(ue,r.sub(le,W)));return r.div(se,ue)},p=(q,W)=>{let $=d.monomial.basis(q,W.length);return _(W,$)},I=(q,W,$,ee=ki)=>{bp(q);let se=W===void 0?K(ee):r.fromBytes(W);if(!$){$=[];for(let Ae=0;Ae<q.min-1;Ae++)$.push(K(ee))}if($.length!==q.min-1)throw new Error("wrong coefficients length");let ue=[se,...$],le=ue.map(Ae=>t.BASE.multiply(Ae));return{coefficients:ue,commitment:le,secret:se}},T={challenge:(q,W,$)=>L(kt(r.toBytes(q),N(W),N($))),compute(q,W,$,ee=ki){if(W.length<1)throw new Error("coefficients should have at least one element");let{point:se,scalar:ue}=O(ee),le=$[0],Ae=this.challenge(q,le,se),ge=r.add(ue,r.mul(W[0],Ae));return g.encode(se,ge)},validate(q,W,$){if(W.length<1)throw new Error("commitment should have at least one element");let{R:ee,z:se}=g.decode($),ue=C(W[0]),le=this.challenge(q,ue,ee);if(!ee.equals(t.BASE.multiply(se).subtract(ue.multiply(le))))throw new Error("invalid proof of knowledge")}},S={challenge:(q,W,$)=>e.challenge?e.challenge(q,W,$):E(kt(N(q),N(W),$)),sign(q,W,$=ki){let{point:ee,scalar:se}=O($),ue=t.BASE.multiply(W),le=this.challenge(ee,ue,q),Ae=r.add(se,r.mul(le,W));return[ee,Ae]},verify(q,W,$,ee){e.adjustPoint&&(ee=e.adjustPoint(ee)),e.adjustPoint&&(W=e.adjustPoint(W));let se=this.challenge(W,ee,q),ue=t.BASE.multiply($),le=ee.multiply(se),Ae=ue.subtract(le).subtract(W);return Ae.clearCofactor&&(Ae=Ae.clearCofactor()),t.ZERO.equals(Ae)}},R=(q,W,$)=>{if(!t.BASE.multiply($).equals(p(q,W)))throw new Error("invalid secret share")},Y={fromNumber(q){if(!Number.isSafeInteger(q))throw new Error("expected safe interger");return G(BigInt(q))},derive(q){if(typeof q!="string")throw new Error("wrong identifier string: "+q);return G(U(xa(q)))}},X=(q,W=ki)=>P(kt(W(32),r.toBytes(q))),ne=(q,W,$)=>{let ee=W.map(ye=>[ye.identifier,B(ye.identifier),C(ye.hiding),C(ye.binding)]);ee.sort((ye,Re)=>ye[1]<Re[1]?-1:ye[1]>Re[1]?1:0);let se=[];for(let[ye,Re,be,_e]of ee)se.push(r.toBytes(Re),N(be),N(_e));let ue=D(kt(...se)),le=kt(N(q),M($),ue),Ae={};for(let[ye,Re]of ee)Ae[ye]=w(kt(le,r.toBytes(Re)));let ge=[],ve=[];for(let[ye,Re,be,_e]of ee){if(t.ZERO.equals(be)||t.ZERO.equals(_e))throw new Error("infinity commitment");ge.push(be,_e),ve.push(r.ONE,Ae[ye])}let sr=_(ge,ve);return{identifiers:ee.map(ye=>ye[1]),groupCommitment:sr,bindingFactors:Ae}},ce=(q,W,$,ee)=>{let se=H(C(q)),ue=B(ee),{identifiers:le,groupCommitment:Ae,bindingFactors:ge}=ne(se,W,$),ve=ge[ee],sr=b(le,ue),xe=S.challenge(Ae,se,$);return{lambda:sr,challenge:xe,bindingFactor:ve,groupCommitment:Ae}};Object.freeze(Y);let pe={Identifier:Y,DKG:Object.freeze({round1:(q,W,$,ee=ki)=>{bp(W);let se=B(q),{coefficients:ue,commitment:le}=I(W,$,void 0,ee),Ae=T.compute(se,ue,le,ee),ge=le.map(N),ve={identifier:G(se),commitment:ge,proofOfKnowledge:Ae},sr={identifier:se,coefficients:ue,commitment:le.map(N),signers:{min:W.min,max:W.max},step:1};return{public:ve,secret:sr}},round2:(q,W)=>{if(W.length!==q.signers.max-1)throw new Error("wrong number of round1 packages");if(!q.coefficients||q.step===3)throw new Error("round3 package used in round2");let $={};for(let ee of W){if(ee.commitment.length!==q.signers.min)throw new Error("wrong number of commitments");let se=B(ee.identifier);if(se===q.identifier)throw new Error("duplicate id="+G(se));T.validate(se,ee.commitment,ee.proofOfKnowledge);for(let le of ee.commitment)C(le);if($[ee.identifier])throw new Error("Duplicate id="+se);let ue=r.toBytes(x(se,q.coefficients));$[ee.identifier]={identifier:G(q.identifier),signingShare:ue}}return q.step=2,$},round3:(q,W,$)=>{if(W.length!==q.signers.max-1)throw new Error("wrong length of round1 packages");if(!q.coefficients||q.step!==2)throw new Error("round2 package used in round3");if($.length!==W.length)throw new Error("wrong length of round2 packages");let ee={};for(let Re of W){if(!Re.identifier||!Re.commitment)throw new Error("wrong round1 share");ee[Re.identifier]={...Re}}for(let Re of $){if(!Re.identifier||!Re.signingShare)throw new Error("wrong round2 share");if(!ee[Re.identifier])throw new Error("round1 share for "+Re.identifier+" is missing");ee[Re.identifier].signingShare=Re.signingShare}if(Object.keys(ee).length!==W.length)throw new Error("mismatch identifiers between rounds");let se=r.ZERO;if(q.commitment.length!==q.signers.min)throw new Error("wrong commitments length");let ue=q.commitment.map(C),le=x(q.identifier,q.coefficients);R(q.identifier,ue,le);let Ae=ue.map(N),ge={[G(q.identifier)]:Ae};for(let Re in ee){let be=ee[Re];if(!be.signingShare||!be.commitment)throw new Error("mismatch identifiers");let _e=B(Re),Qi=r.fromBytes(be.signingShare),Me=be.commitment.map(C);R(q.identifier,Me,Qi),se=r.add(se,Qi);let ke=G(_e);if(ge[ke])throw new Error("duplicated id="+ke);ge[ke]=be.commitment}se=r.add(se,le);let ve=new Array(q.signers.min).fill(t.ZERO);for(let Re in ge){let be=ge[Re];if(be.length!==q.signers.min)throw new Error("wrong commitments length");for(let _e=0;_e<be.length;_e++)ve[_e]=ve[_e].add(C(be[_e]))}let sr=ve.map(N),xe={};for(let Re in ge)xe[Re]=N(p(B(Re),ve));let ye={public:{signers:{min:q.signers.min,max:q.signers.max},commitments:sr,verifyingShares:Object.fromEntries(Object.entries(xe).map(([Re,be])=>[Re,be.slice()]))},secret:{identifier:G(q.identifier),signingShare:r.toBytes(se)}};e.adjustDKG&&(ye=e.adjustDKG(ye));for(let Re=0;Re<q.coefficients.length;Re++)q.coefficients[Re]-=q.coefficients[Re];return delete q.coefficients,q.step=3,ye},clean(q){if(q.identifier-=q.identifier,q.coefficients)for(let W=0;W<q.coefficients.length;W++)q.coefficients[W]-=q.coefficients[W];q.step=3}}),trustedDealer(q,W,$,ee=ki){if(bp(q),W===void 0){W=[];for(let ve=1;ve<=q.max;ve++)W.push(Y.fromNumber(ve))}else if(!Array.isArray(W)||W.length!==q.max)throw new Error("identifiers should be array of "+q.max);let se={};for(let ve of W){let sr=B(ve);if(ve in se)throw new Error("duplicated id="+ve);se[ve]=sr}let ue=I(q,$,void 0,ee),le=ue.commitment.map(N),Ae={},ge={};for(let ve of W){let sr=x(se[ve],ue.coefficients);ge[ve]=N(t.BASE.multiply(sr)),Ae[ve]={identifier:ve,signingShare:r.toBytes(sr)}}return{public:{signers:{min:q.min,max:q.max},commitments:le,verifyingShares:ge},secretShares:Ae}},validateSecret(q,W){let $=B(q.identifier),ee=W.commitments.map(C),se=r.fromBytes(q.signingShare);R($,ee,se)},commit(q,W=ki){let $=r.fromBytes(q.signingShare),ee=X($,W),se=X($,W),ue={hiding:r.toBytes(ee),binding:r.toBytes(se)};return{nonces:ue,commitments:F(q.identifier,ue)}},signShare(q,W,$,ee,se){vA(W.signers,ee.length);let ue=r.fromBytes($.hiding),le=r.fromBytes($.binding);if(r.is0(ue)||r.is0(le))throw new Error("signing nonces already used");let Ae={identifier:q.identifier,hiding:N(t.BASE.multiply(ue)),binding:N(t.BASE.multiply(le))},ge=ee.find(Ce=>Ce.identifier===q.identifier);if(!ge)throw new Error("missing signer commitment");if(Ia(ge.hiding)!==Ia(Ae.hiding)||Ia(ge.binding)!==Ia(Ae.binding))throw new Error("incorrect signer commitment");e.adjustSecret&&(q=e.adjustSecret(q,W)),e.adjustPublic&&(W=e.adjustPublic(W));let ve=r.fromBytes(q.signingShare),{lambda:sr,challenge:xe,bindingFactor:ye,groupCommitment:Re}=ce(W.commitments[0],ee,se,q.identifier),be=e.adjustNonces?e.adjustNonces(Re,$):$,_e=e.adjustNonces?r.fromBytes(be.hiding):ue,Qi=e.adjustNonces?r.fromBytes(be.binding):le,Me=r.mul(r.mul(sr,ve),xe),ke=r.mul(Qi,ye),$s=r.toBytes(r.add(r.add(_e,ke),Me));return $.hiding.fill(0),$.binding.fill(0),$s},verifyShare(q,W,$,ee,se){e.adjustPublic&&(q=e.adjustPublic(q));let ue=W.find(Qi=>Qi.identifier===ee);if(!ue)throw new Error("cannot find identifier commitment");let le=C(q.verifyingShares[ee]),Ae=C(ue.hiding),ge=C(ue.binding),{lambda:ve,challenge:sr,bindingFactor:xe,groupCommitment:ye}=ce(q.commitments[0],W,$,ee),Re=Ae.add(ge.multiply(xe));e.adjustGroupCommitmentShare&&(Re=e.adjustGroupCommitmentShare(ye,Re));let be=t.BASE.multiply(r.fromBytes(se)),_e=Re.add(le.multiply(r.mul(sr,ve)));return be.equals(_e)},aggregate(q,W,$,ee){e.adjustPublic&&(q=e.adjustPublic(q));try{vA(q.signers,W.length)}catch{throw new Gc("aggregation failed",[])}let se=W.map(ge=>ge.identifier);if(se.length!==Object.keys(ee).length)throw new Gc("aggregation failed",[]);for(let ge of se)if(!(ge in ee)||!(ge in q.verifyingShares))throw new Gc("aggregation failed",[]);let ue=C(q.commitments[0]),{groupCommitment:le}=ne(ue,W,$),Ae=r.ZERO;for(let ge of se)Ae=r.add(Ae,r.fromBytes(ee[ge]));if(!S.verify($,le,Ae,ue)){let ge=[];for(let ve of se)this.verifyShare(q,W,$,ve,ee[ve])||ge.push(ve);throw new Gc("aggregation failed",ge)}return g.encode(le,Ae)},sign(q,W){let $=r.fromBytes(W);e.adjustScalar&&($=e.adjustScalar($));let[ee,se]=S.sign(q,$);return g.encode(ee,se)},verify(q,W,$){let ee=e.parsePublicKey?e.parsePublicKey($):C($),{R:se,z:ue}=g.decode(q);return S.verify(W,se,ue,ee)},combineSecret(q,W){if(bp(W),!Array.isArray(q)||q.length<W.min)throw new Error("wrong secret shares array");let $=[],ee={};for(let le of q){let Ae=B(le.identifier),ge=G(Ae);if(ee[ge])throw new Error("duplicated id="+ge);ee[ge]=!0,$.push([Ae,r.fromBytes(le.signingShare)])}let se=$.map(([le])=>le),ue=r.ZERO;for(let[le,Ae]of $)ue=r.add(ue,r.mul(Ae,b(se,le)));return r.toBytes(ue)},utils:Object.freeze({Fn:r,randomScalar:(q=ki)=>r.toBytes(O(q).scalar),generateSecretPolynomial:(q,W,$,ee)=>{let se=I(q,W,$,ee);return{...se,commitment:se.commitment.map(N)}}})};return Object.freeze(pe)}var bp,vA,Gc,mA=Xr(()=>{v();gs();Ju();yp();lA();Kc();bp=e=>{if(!Number.isSafeInteger(e.min)||!Number.isSafeInteger(e.max))throw new Error("Wrong signers info: min="+e.min+" max="+e.max);if(e.min<2||e.max<2||e.min>e.max)throw new Error("Wrong signers info: min="+e.min+" max="+e.max)},vA=(e,t)=>{if(t<e.min||t>e.max)throw new Error("Wrong number of commitments="+t)},Gc=class extends Error{constructor(r,i){super(r);Z(this,"cheaters");this.cheaters=i}}});var py={};Q1(py,{_HMAC:()=>h0,hmac:()=>dy});var h0,dy,_p=Xr(()=>{v();gs();h0=class{constructor(t,r){Z(this,"oHash");Z(this,"iHash");Z(this,"blockLen");Z(this,"outputLen");Z(this,"canXOF",!1);Z(this,"finished",!1);Z(this,"destroyed",!1);if(X2(t),Eo(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=t.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Sa(n)}update(t){return Dc(this),this.iHash.update(t),this}digestInto(t){Dc(this),J2(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:i,finished:n,destroyed:o,blockLen:a,outputLen:s}=this;return t=t,t.finished=n,t.destroyed=o,t.blockLen=a,t.outputLen=s,t.oHash=r._cloneInto(t.oHash),t.iHash=i._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},dy=(()=>{let e=((t,r,i)=>new h0(t,r).update(i).digest());return e.create=(t,r)=>new h0(t,r),e})()});function Q$(e,t,r){ry("scalar",e,gn,r);let[[i,n],[o,a]]=t,s=yA(a*e,r),u=yA(-n*e,r),c=e-s*i-u*o,l=-s*n-u*a,m=c<gn,w=l<gn;m&&(c=-c),w&&(l=-l);let E=Hc(Math.ceil(Xu(r)/2))+Kr;if(c<gn||c>=E||l<gn||l>=E)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:c,k2neg:w,k2:l}}function vy(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function gy(e,t){pn(e);let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];return $u(r.lowS,"lowS"),$u(r.prehash,"prehash"),r.format!==void 0&&vy(r.format),r}function bA(e,t={}){let r=uA("weierstrass",e,t),i=r.Fp,n=r.Fn,o=r.CURVE,{h:a,n:s}=o;pn(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:u,allowInfinityPoint:c}=t;if(u&&(!i.is0(o.a)||typeof u.beta!="bigint"||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=SA(i,n);function m(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function w(O,y,f){if(c&&y.is0())return Uint8Array.of(0);let{x:d,y:_}=y.toAffine(),x=i.toBytes(d);if($u(f,"isCompressed"),f){m();let b=!i.isOdd(_);return kt(_A(b),x)}else return kt(Uint8Array.of(4),x,i.toBytes(_))}function E(O){qt(O,void 0,"Point");let{publicKey:y,publicKeyUncompressed:f}=l,d=O.length,_=O[0],x=O.subarray(1);if(c&&d===1&&_===0)return{x:i.ZERO,y:i.ZERO};if(d===y&&(_===2||_===3)){let b=i.fromBytes(x);if(!i.isValid(b))throw new Error("bad point: is not on curve, wrong x");let p=D(b),I;try{I=i.sqrt(p)}catch(R){let Y=R instanceof Error?": "+R.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}m();let T=i.isOdd(I);return(_&1)===1!==T&&(I=i.neg(I)),{x:b,y:I}}else if(d===f&&_===4){let b=i.BYTES,p=i.fromBytes(x.subarray(0,b)),I=i.fromBytes(x.subarray(b,b*2));if(!L(p,I))throw new Error("bad point: is not on curve");return{x:p,y:I}}else throw new Error(`bad point: got length ${d}, expected compressed=${y} or uncompressed=${f}`)}let P=t.toBytes===void 0?w:t.toBytes,M=t.fromBytes===void 0?E:t.fromBytes;function D(O){let y=i.sqr(O),f=i.mul(y,O);return i.add(i.add(f,i.mul(O,o.a)),o.b)}function L(O,y){let f=i.sqr(y),d=D(O);return i.eql(f,d)}if(!L(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let U=i.mul(i.pow(o.a,Zc),yy),K=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(U,K)))throw new Error("bad curve params: a or b");function N(O,y,f=!1){if(!i.isValid(y)||f&&i.is0(y))throw new Error(`bad point coordinate ${O}`);return y}function C(O){if(!(O instanceof z))throw new Error("Weierstrass Point expected")}function F(O){if(!u||!u.basises)throw new Error("no endo");return Q$(O,u.basises,n.ORDER)}function H(O,y,f,d,_){return f=new z(i.mul(f.X,O),f.Y,f.Z),y=l0(d,y),f=l0(_,f),y.add(f)}let g=class g{constructor(y,f,d){Z(this,"X");Z(this,"Y");Z(this,"Z");this.X=N("x",y),this.Y=N("y",f,!0),this.Z=N("z",d),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){let{x:f,y:d}=y||{};if(!y||!i.isValid(f)||!i.isValid(d))throw new Error("invalid affine point");if(y instanceof g)throw new Error("projective point not allowed");return i.is0(f)&&i.is0(d)?g.ZERO:new g(f,d,i.ONE)}static fromBytes(y){let f=g.fromAffine(M(qt(y,void 0,"point")));return f.assertValidity(),f}static fromHex(y){return g.fromBytes(qc(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,f=!0){return B.createCache(this,y),f||this.multiply(Zc),this}assertValidity(){let y=this;if(y.is0()){if(t.allowInfinityPoint&&i.is0(y.X)&&i.eql(y.Y,i.ONE)&&i.is0(y.Z))return;throw new Error("bad point: ZERO")}let{x:f,y:d}=y.toAffine();if(!i.isValid(f)||!i.isValid(d))throw new Error("bad point: x or y not field elements");if(!L(f,d))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(y)}equals(y){C(y);let{X:f,Y:d,Z:_}=this,{X:x,Y:b,Z:p}=y,I=i.eql(i.mul(f,p),i.mul(x,_)),T=i.eql(i.mul(d,p),i.mul(b,_));return I&&T}negate(){return new g(this.X,i.neg(this.Y),this.Z)}double(){let{a:y,b:f}=o,d=i.mul(f,Zc),{X:_,Y:x,Z:b}=this,p=i.ZERO,I=i.ZERO,T=i.ZERO,S=i.mul(_,_),R=i.mul(x,x),Y=i.mul(b,b),X=i.mul(_,x);return X=i.add(X,X),T=i.mul(_,b),T=i.add(T,T),p=i.mul(y,T),I=i.mul(d,Y),I=i.add(p,I),p=i.sub(R,I),I=i.add(R,I),I=i.mul(p,I),p=i.mul(X,p),T=i.mul(d,T),Y=i.mul(y,Y),X=i.sub(S,Y),X=i.mul(y,X),X=i.add(X,T),T=i.add(S,S),S=i.add(T,S),S=i.add(S,Y),S=i.mul(S,X),I=i.add(I,S),Y=i.mul(x,b),Y=i.add(Y,Y),S=i.mul(Y,X),p=i.sub(p,S),T=i.mul(Y,R),T=i.add(T,T),T=i.add(T,T),new g(p,I,T)}add(y){C(y);let{X:f,Y:d,Z:_}=this,{X:x,Y:b,Z:p}=y,I=i.ZERO,T=i.ZERO,S=i.ZERO,R=o.a,Y=i.mul(o.b,Zc),X=i.mul(f,x),ne=i.mul(d,b),ce=i.mul(_,p),pe=i.add(f,d),q=i.add(x,b);pe=i.mul(pe,q),q=i.add(X,ne),pe=i.sub(pe,q),q=i.add(f,_);let W=i.add(x,p);return q=i.mul(q,W),W=i.add(X,ce),q=i.sub(q,W),W=i.add(d,_),I=i.add(b,p),W=i.mul(W,I),I=i.add(ne,ce),W=i.sub(W,I),S=i.mul(R,q),I=i.mul(Y,ce),S=i.add(I,S),I=i.sub(ne,S),S=i.add(ne,S),T=i.mul(I,S),ne=i.add(X,X),ne=i.add(ne,X),ce=i.mul(R,ce),q=i.mul(Y,q),ne=i.add(ne,ce),ce=i.sub(X,ce),ce=i.mul(R,ce),q=i.add(q,ce),X=i.mul(ne,q),T=i.add(T,X),X=i.mul(W,q),I=i.mul(pe,I),I=i.sub(I,X),X=i.mul(pe,ne),S=i.mul(W,S),S=i.add(S,X),new g(I,T,S)}subtract(y){return C(y),this.add(y.negate())}is0(){return this.equals(g.ZERO)}multiply(y){let{endo:f}=t;if(!n.isValidNot0(y))throw new RangeError("invalid scalar: out of range");let d,_,x=b=>B.cached(this,b,p=>fy(g,p));if(f){let{k1neg:b,k1:p,k2neg:I,k2:T}=F(y),{p:S,f:R}=x(p),{p:Y,f:X}=x(T);_=R.add(X),d=H(f.beta,S,Y,b,I)}else{let{p:b,f:p}=x(y);d=b,_=p}return fy(g,[d,_])[0]}multiplyUnsafe(y){let{endo:f}=t,d=this,_=y;if(!n.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===gn||d.is0())return g.ZERO;if(_===Kr)return d;if(B.hasCache(this))return this.multiply(_);if(f){let{k1neg:x,k1:b,k2neg:p,k2:I}=F(_),{p1:T,p2:S}=aA(g,d,b,I);return H(f.beta,T,S,x,p)}else return B.unsafe(d,_)}toAffine(y){let f=this,d=y,{X:_,Y:x,Z:b}=f;if(i.eql(b,i.ONE))return{x:_,y:x};let p=f.is0();d==null&&(d=p?i.ONE:i.inv(b));let I=i.mul(_,d),T=i.mul(x,d),S=i.mul(b,d);if(p)return{x:i.ZERO,y:i.ZERO};if(!i.eql(S,i.ONE))throw new Error("invZ was invalid");return{x:I,y:T}}isTorsionFree(){let{isTorsionFree:y}=t;return a===Kr?!0:y?y(g,this):B.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:y}=t;return a===Kr?this:y?y(g,this):this.multiplyUnsafe(a)}isSmallOrder(){return a===Kr?this.is0():this.clearCofactor().is0()}toBytes(y=!0){return $u(y,"isCompressed"),this.assertValidity(),P(g,this,y)}toHex(y=!0){return Ia(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};Z(g,"BASE",new g(o.Gx,o.Gy,i.ONE)),Z(g,"ZERO",new g(i.ZERO,i.ONE,i.ZERO)),Z(g,"Fp",i),Z(g,"Fn",n);let z=g,G=n.BITS,B=new vp(z,t.endo?Math.ceil(G/2):G);return G>=8&&z.BASE.precompute(8),Object.freeze(z.prototype),Object.freeze(z),z}function _A(e){return Uint8Array.of(e?2:3)}function eX(e,t){let r=ef(e),i=r.ORDER,n=gn;for(let M=i-Kr;M%Io===gn;M/=Io)n+=Kr;let o=n,a=Io<<o-Kr-Kr,s=a*Io,u=(i-Kr)/s,c=(u-Kr)/Io,l=s-Kr,m=a,w=r.pow(t,u),E=r.pow(t,(u+Kr)/Io),P=(M,D)=>{let L=w,U=r.pow(D,l),K=r.sqr(U);K=r.mul(K,D);let N=r.mul(M,K);N=r.pow(N,c),N=r.mul(N,U),U=r.mul(N,D),K=r.mul(N,M);let C=r.mul(K,U);N=r.pow(C,m);let F=r.eql(N,r.ONE);U=r.mul(K,E),N=r.mul(C,L),K=r.cmov(U,K,F),C=r.cmov(N,C,F);for(let H=o;H>Kr;H--){let z=H-Io;z=Io<<z-Kr;let G=r.pow(C,z),B=r.eql(G,r.ONE);U=r.mul(K,L),L=r.mul(L,L),G=r.mul(C,L),K=r.cmov(U,K,B),C=r.cmov(G,C,B)}return{isValid:!r.is0(D)&&(F||r.is0(M)),value:K}};if(r.ORDER%yy===Zc){let M=(r.ORDER-Zc)/yy,D=r.sqrt(r.neg(t));P=(L,U)=>{let K=r.sqr(U),N=r.mul(L,U);K=r.mul(K,N);let C=r.pow(K,M);C=r.mul(C,N);let F=r.mul(C,D),H=r.mul(r.sqr(C),U),z=r.eql(H,L),G=r.cmov(F,C,z);return{isValid:!r.is0(U)&&z,value:G}}}return P}function wA(e,t){let r=ef(e),{A:i,B:n,Z:o}=t;if(!r.isValidNot0(i)||!r.isValidNot0(n)||!r.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");if(r.eql(o,r.neg(r.ONE))||oy(r,o))throw new Error("mapToCurveSimpleSWU: invalid opts");let a=r.mul(n,r.inv(r.mul(o,i))),s=r.add(r.add(r.mul(r.sqr(a),a),r.mul(i,a)),n);if(!oy(r,s))throw new Error("mapToCurveSimpleSWU: invalid opts");let u=eX(r,o);if(!r.isOdd)throw new Error("Field does not have .isOdd()");return c=>{let l,m,w,E,P,M,D,L;l=r.sqr(c),l=r.mul(l,o),m=r.sqr(l),m=r.add(m,l),w=r.add(m,r.ONE),w=r.mul(w,n),E=r.cmov(o,r.neg(m),!r.eql(m,r.ZERO)),E=r.mul(E,i),m=r.sqr(w),M=r.sqr(E),P=r.mul(M,i),m=r.add(m,P),m=r.mul(m,w),M=r.mul(M,E),P=r.mul(M,n),m=r.add(m,P),D=r.mul(l,w);let{isValid:U,value:K}=u(m,M);L=r.mul(l,c),L=r.mul(L,K),D=r.cmov(D,w,U),L=r.cmov(L,K,U);let N=r.isOdd(c)===r.isOdd(L);L=r.cmov(r.neg(L),L,N);let C=tf(r,[E],!0)[0];return D=r.mul(D,C),{x:D,y:L}}}function SA(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function tX(e,t={}){let{Fn:r}=e,i=t.randomBytes===void 0?ki:t.randomBytes,n=Object.assign(SA(e.Fp,r),{seed:Math.max(c0(r.ORDER),16)});function o(E){try{let P=r.fromBytes(E);return r.isValidNot0(P)}catch{return!1}}function a(E,P){let{publicKey:M,publicKeyUncompressed:D}=n;try{let L=E.length;return P===!0&&L!==M||P===!1&&L!==D?!1:!!e.fromBytes(E)}catch{return!1}}function s(E){return E=E===void 0?i(n.seed):E,zc(qt(E,n.seed,"seed"),r.ORDER)}function u(E,P=!0){return e.BASE.multiply(r.fromBytes(E)).toBytes(P)}function c(E){let{secretKey:P,publicKey:M,publicKeyUncompressed:D}=n,L=r._lengths;if(!Yu(E))return;let U=qt(E,void 0,"key").length,K=U===M||U===D,N=U===P||!!L?.includes(U);if(!(K&&N))return K}function l(E,P,M=!0){if(c(E)===!0)throw new Error("first arg must be private key");if(c(P)===!1)throw new Error("second arg must be public key");let D=r.fromBytes(E);return e.fromBytes(P).multiply(D).toBytes(M)}let m={isValidSecretKey:o,isValidPublicKey:a,randomSecretKey:s},w=mp(s,u);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:u,getSharedSecret:l,keygen:w,Point:e,utils:m,lengths:n})}function xA(e,t,r={}){let i=t;X2(i),pn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?ki:r.randomBytes,o=r.hmac===void 0?(d,_)=>dy(i,d,_):r.hmac,{Fp:a,Fn:s}=e,{ORDER:u,BITS:c}=s,{keygen:l,getPublicKey:m,getSharedSecret:w,utils:E,lengths:P}=tX(e,r),M={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},D=u*Io+Kr<a.ORDER;function L(d){let _=u>>Kr;return d>_}function U(d,_){if(!s.isValidNot0(_))throw new Error(`invalid signature ${d}: out of range 1..Point.Fn.ORDER`);return _}function K(){if(D)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N(d,_){vy(_);let x=P.signature,b=_==="compact"?x:_==="recovered"?x+1:void 0;return qt(d,b)}class C{constructor(_,x,b){Z(this,"r");Z(this,"s");Z(this,"recovery");if(this.r=U("r",_),this.s=U("s",x),b!=null){if(K(),![0,1,2,3].includes(b))throw new Error("invalid recovery id");this.recovery=b}Object.freeze(this)}static fromBytes(_,x=M.format){N(_,x);let b;if(x==="der"){let{r:S,s:R}=Hn.toSig(qt(_));return new C(S,R)}x==="recovered"&&(b=_[0],x="compact",_=_.subarray(1));let p=P.signature/2,I=_.subarray(0,p),T=_.subarray(p,p*2);return new C(s.fromBytes(I),s.fromBytes(T),b)}static fromHex(_,x){return this.fromBytes(qc(_),x)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new C(this.r,this.s,_)}recoverPublicKey(_){let{r:x,s:b}=this,p=this.assertRecovery(),I=p===2||p===3?x+u:x;if(!a.isValid(I))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=a.toBytes(I),S=e.fromBytes(kt(_A((p&1)===0),T)),R=s.inv(I),Y=H(qt(_,void 0,"msgHash")),X=s.create(-Y*R),ne=s.create(b*R),ce=e.BASE.multiplyUnsafe(X).add(S.multiplyUnsafe(ne));if(ce.is0())throw new Error("invalid recovery: point at infinify");return ce.assertValidity(),ce}hasHighS(){return L(this.s)}toBytes(_=M.format){if(vy(_),_==="der")return qc(Hn.hexFromSig(this));let{r:x,s:b}=this,p=s.toBytes(x),I=s.toBytes(b);return _==="recovered"?(K(),kt(Uint8Array.of(this.assertRecovery()),p,I)):kt(p,I)}toHex(_){return Ia(this.toBytes(_))}}Object.freeze(C.prototype),Object.freeze(C);let F=r.bits2int===void 0?function(_){if(_.length>8192)throw new Error("input is too large");let x=bi(_),b=_.length*8-c;return b>0?x>>BigInt(b):x}:r.bits2int,H=r.bits2int_modN===void 0?function(_){return s.create(F(_))}:r.bits2int_modN,z=Hc(c);function G(d){return ry("num < 2^"+c,d,gn,z),s.toBytes(d)}function B(d,_){return qt(d,void 0,"message"),_?qt(i(d),void 0,"prehashed message"):d}function g(d,_,x){let{lowS:b,prehash:p,extraEntropy:I}=gy(x,M);d=B(d,p);let T=H(d),S=s.fromBytes(_);if(!s.isValidNot0(S))throw new Error("invalid private key");let R=[G(S),G(T)];if(I!=null&&I!==!1){let ce=I===!0?n(P.secretKey):I;R.push(qt(ce,void 0,"extraEntropy"))}let Y=kt(...R),X=T;function ne(ce){let pe=F(ce);if(!s.isValidNot0(pe))return;let q=s.inv(pe),W=e.BASE.multiply(pe).toAffine(),$=s.create(W.x);if($===gn)return;let ee=s.create(q*s.create(X+$*S));if(ee===gn)return;let se=(W.x===$?0:2)|Number(W.y&Kr),ue=ee;return b&&L(ee)&&(ue=s.neg(ee),se^=1),new C($,ue,D?void 0:se)}return{seed:Y,k2sig:ne}}function O(d,_,x={}){let{seed:b,k2sig:p}=g(d,_,x);return zI(i.outputLen,s.BYTES,o)(b,p).toBytes(x.format)}function y(d,_,x,b={}){let{lowS:p,prehash:I,format:T}=gy(b,M);if(x=qt(x,void 0,"publicKey"),_=B(_,I),!Yu(d)){let S=d instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}N(d,T);try{let S=C.fromBytes(d,T),R=e.fromBytes(x);if(p&&S.hasHighS())return!1;let{r:Y,s:X}=S,ne=H(_),ce=s.inv(X),pe=s.create(ne*ce),q=s.create(Y*ce),W=e.BASE.multiplyUnsafe(pe).add(R.multiplyUnsafe(q));return W.is0()?!1:s.create(W.x)===Y}catch{return!1}}function f(d,_,x={}){let{prehash:b}=gy(x,M);return _=B(_,b),C.fromBytes(d,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:m,getSharedSecret:w,utils:E,lengths:P,Point:e,sign:O,verify:y,recoverPublicKey:f,Signature:C,hash:i})}var yA,my,Hn,gn,Kr,Io,Zc,yy,EA=Xr(()=>{v();_p();gs();Ju();yp();Kc();yA=(e,t)=>(e+(e>=0?t:-t)/Io)/t;my=class extends Error{constructor(t=""){super(t)}},Hn={Err:my,_tlv:{encode:(e,t)=>{let{Err:r}=Hn;if(dn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let i=t.length/2,n=f0(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?f0(n.length/2|128):"";return f0(e)+o+n+t},decode(e,t){let{Err:r}=Hn;t=qt(t,void 0,"DER data");let i=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),a=0;if(!o)a=n;else{let u=n&127;if(!u)throw new r("tlv.decode(long): indefinite length not supported");if(u>4)throw new r("tlv.decode(long): byte length is too big");let c=t.subarray(i,i+u);if(c.length!==u)throw new r("tlv.decode: length bytes not complete");if(c[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of c)a=a<<8|l;if(i+=u,a<128)throw new r("tlv.decode(long): not minimal encoding")}let s=t.subarray(i,i+a);if(s.length!==a)throw new r("tlv.decode: wrong value length");return{v:s,l:t.subarray(i+a)}}},_int:{encode(e){let{Err:t}=Hn;if(hp(e),e<gn)throw new t("integer: negative integers are not allowed");let r=f0(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Hn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return bi(e)}},toSig(e){let{Err:t,_int:r,_tlv:i}=Hn,n=qt(e,void 0,"signature"),{v:o,l:a}=i.decode(48,n);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:s,l:u}=i.decode(2,o),{v:c,l}=i.decode(2,u);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(c)}},hexFromSig(e){let{_tlv:t,_int:r}=Hn,i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}};Object.freeze(Hn._tlv);Object.freeze(Hn._int);Object.freeze(Hn);gn=BigInt(0),Kr=BigInt(1),Io=BigInt(2),Zc=BigInt(3),yy=BigInt(4)});var p0={};Q1(p0,{__TEST:()=>aX,schnorr:()=>sX,schnorr_FROST:()=>pX,secp256k1:()=>nX,secp256k1_FROST:()=>cX,secp256k1_hasher:()=>wy});function iX(e){let t=wp.p,r=BigInt(3),i=BigInt(6),n=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),u=BigInt(88),c=e*e*e%t,l=c*c*e%t,m=Fi(l,r,t)*l%t,w=Fi(m,r,t)*l%t,E=Fi(w,by,t)*c%t,P=Fi(E,n,t)*E%t,M=Fi(P,o,t)*P%t,D=Fi(M,s,t)*M%t,L=Fi(D,u,t)*D%t,U=Fi(L,s,t)*M%t,K=Fi(U,r,t)*l%t,N=Fi(K,a,t)*P%t,C=Fi(N,i,t)*c%t,F=Fi(C,by,t);if(!Aa.eql(Aa.sqr(F),e))throw new Error("Cannot find square root");return F}function d0(e,...t){let r=OA[e];if(r===void 0){let i=bs(Fc(e));r=kt(i,i),OA[e]=r}return bs(kt(r,...t))}function TA(e){let{Fn:t,BASE:r}=Ut,i=t.fromBytes(e),n=r.multiply(i);return{scalar:Ao(n.y)?i:t.neg(i),bytes:of(n)}}function Sp(e){let t=Aa;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x \u2265 p");let r=t.create(e*e),i=t.create(r*e+BigInt(7)),n=t.sqrt(i);Ao(n)||(n=t.neg(n));let o=Ut.fromAffine({x:e,y:n});return o.assertValidity(),o}function _y(...e){return Ut.Fn.create(Wc(d0("BIP0340/challenge",...e)))}function IA(e){return TA(e).bytes}function oX(e,t,r=o0(32)){let{Fn:i,BASE:n}=Ut,o=qt(e,void 0,"message"),{bytes:a,scalar:s}=TA(t),u=qt(r,32,"auxRand"),c=i.toBytes(s^Wc(d0("BIP0340/aux",u))),l=d0("BIP0340/nonce",c,a,o),m=i.create(Wc(l));if(m===0n)throw new Error("sign failed: k is zero");let w=n.multiply(m),E=Ao(w.y)?m:i.neg(m),P=of(w),M=_y(P,a,o),D=new Uint8Array(64);if(D.set(P,0),D.set(i.toBytes(i.create(E+M*s)),32),!kA(D,o,a))throw new Error("sign: Invalid signature produced");return D}function kA(e,t,r){let{Fp:i,Fn:n,BASE:o}=Ut,a=qt(e,64,"signature"),s=qt(t,void 0,"message"),u=qt(r,32,"publicKey");try{let c=Sp(Wc(u)),l=Wc(a.subarray(0,32));if(!i.isValidNot0(l))return!1;let m=Wc(a.subarray(32,64));if(!n.isValidNot0(m))return!1;let w=_y(n.toBytes(l),of(c),s),E=o.multiplyUnsafe(m).add(c.multiplyUnsafe(n.neg(w))),{x:P,y:M}=E.toAffine();return!(E.is0()||!Ao(M)||P!==l)}catch{return!1}}function RA(e,t){if(t===void 0)return PA;let r=of(e),i=bi(d0("TapTweak",r,t));if(!Ut.Fn.isValid(i))throw new Error("invalid TapTweak hash");return i}function Sy(e){let t=Ut.fromBytes(e.commitments[0]);return Ao(t.y)?e:{signers:{min:e.signers.min,max:e.signers.max},commitments:e.commitments.map(r=>Ut.fromBytes(r).negate().toBytes()),verifyingShares:Object.fromEntries(Object.entries(e.verifyingShares).map(([r,i])=>[r,Ut.fromBytes(i).negate().toBytes()]))}}function BA(e,t){let r=Ut.fromBytes(t.commitments[0]);if(Ao(r.y))return e;let i=Ut.Fn;return{...e,signingShare:i.toBytes(i.neg(i.fromBytes(e.signingShare)))}}function lX(e,t){if(Ao(e.y))return t;let r=Ut.Fn;return{binding:r.toBytes(r.neg(r.fromBytes(t.binding))),hiding:r.toBytes(r.neg(r.fromBytes(t.hiding)))}}function hX(e,t,r){let i=Ut.Fn,n=BA(e,t),o=Sy(t),a=RA(Ut.fromBytes(o.commitments[0]),r),s=i.toBytes(i.add(i.fromBytes(n.signingShare),a));return{identifier:n.identifier,signingShare:s}}function dX(e,t){let r=Sy(e),i=RA(Ut.fromBytes(r.commitments[0]),t),n=Ut.BASE.multiply(i),o=r.commitments.map((s,u)=>(u===0?Ut.fromBytes(s).add(n):Ut.fromBytes(s)).toBytes()),a={};for(let s in r.verifyingShares)a[s]=Ut.fromBytes(r.verifyingShares[s]).add(n).toBytes();return{signers:{min:r.signers.min,max:r.signers.max},commitments:o,verifyingShares:a}}var wp,rX,PA,by,Aa,Ut,nX,OA,of,Ao,Wc,aX,sX,uX,AA,fX,wy,cX,pX,g0=Xr(()=>{v();fp();gs();yp();mA();gA();Kc();EA();Ju();wp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},rX={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},PA=BigInt(0),by=BigInt(2);Aa=jc(wp.p,{sqrt:iX}),Ut=bA(wp,{Fp:Aa,endo:rX}),nX=xA(Ut,bs),OA={};of=e=>e.toBytes(!0).slice(1),Ao=e=>e%by===PA;Wc=bi;aX=Object.freeze({lift_x:Sp}),sX=(()=>{let r=i=>(i=i===void 0?o0(48):i,zc(i,wp.n));return Object.freeze({keygen:mp(r,IA),getPublicKey:IA,sign:oX,verify:kA,Point:Ut,utils:Object.freeze({randomSecretKey:r,taggedHash:d0,lift_x:Sp,pointToBytes:of}),lengths:Object.freeze({secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48})})})(),uX=dA(Aa,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),fX=()=>AA||(AA=wA(Aa,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Aa.create(BigInt("-11"))})),wy=pA(Ut,e=>{let{x:t,y:r}=fX()(Aa.create(e[0]));return uX(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Aa.ORDER,m:1,k:128,expand:"xmd",hash:bs}),cX=hy({name:"FROST-secp256k1-SHA256-v1",Point:Ut,hashToScalar:wy.hashToScalar,hash:bs});pX=hy({name:"FROST-secp256k1-SHA256-TR-v1",Point:Ut,hashToScalar:wy.hashToScalar,hash:bs,parsePublicKey(e){if(e.length===32)return Sp(bi(e));if(e.length===33)return Ut.fromBytes(e);throw new Error(`expected x-only or compressed public key, got length=${e.length}`)},adjustScalar(e){let t=Ut.BASE.multiply(e);return Ao(t.y)?e:Ut.Fn.neg(e)},adjustPoint:e=>Ao(e.y)?e:e.negate(),challenge(e,t,r){return _y(of(e),of(t),r)},adjustNonces:lX,adjustGroupCommitmentShare:(e,t)=>Ao(e.y)?t:t.negate(),adjustPublic:Sy,adjustSecret:BA,adjustTx:{encode:e=>e.subarray(1),decode:e=>kt(Uint8Array.of(2),e)},adjustDKG:e=>{let t=new Uint8Array(0);return{public:dX(e.public,t),secret:hX(e.secret,e.public,t)}}})});var vn=k((_2e,DA)=>{"use strict";v();var MA=fr(),{secp256k1:gX}=(g0(),lo(p0)),m0=gX.Point,xp=m0.Fn.ORDER;function vX(e){return BigInt("0x"+(e.toString(16)||"0"))}function xy(e){var t=e.toString(16);return t.length%2&&(t="0"+t),new MA(t,16)}function Ep(e){if(e==null)throw new Error("Invalid Point");if(typeof e=="bigint")return e;if(typeof e=="number")return BigInt(e);if(typeof e=="string")return BigInt(e.indexOf("0x")===0?e:"0x"+e);if(typeof e.toString=="function")return vX(e);throw new Error("Invalid Point")}function v0(e){var t=Object.create(Ft.prototype);return t._p=e,t}function NA(e,t){var r=Ep(t).toString(16).padStart(64,"0");return m0.fromHex((e?"03":"02")+r)}function CA(e,t){var r;try{r=NA((t&1n)===1n,e)}catch{throw new Error("Point does not lie on the curve")}if(r.toAffine().y!==t)throw new Error("Invalid y value for curve.")}function Ft(e,t,r){if(!(this instanceof Ft))return new Ft(e,t,r);var i,n;try{i=Ep(e),n=Ep(t)}catch{throw new Error("Invalid Point")}CA(i,n);try{this._p=m0.fromAffine({x:i,y:n})}catch{throw new Error("Invalid Point")}return this}Ft.fromX=function(t,r){try{var i=v0(NA(t,r))}catch{throw new Error("Invalid X")}return i.validate(),i};Ft.getG=function(){return v0(m0.BASE)};Ft.getN=function(){return xy(xp)};Ft.prototype.getX=function(){return xy(this._p.toAffine().x)};Ft.prototype.getY=function(){return xy(this._p.toAffine().y)};Object.defineProperty(Ft.prototype,"x",{configurable:!0,enumerable:!0,get:function(){return this.getX()}});Object.defineProperty(Ft.prototype,"y",{configurable:!0,enumerable:!0,get:function(){return this.getY()}});Ft.prototype.mul=function(t){var r=(Ep(t)%xp+xp)%xp;return r===0n||this._p.is0()?v0(m0.ZERO):v0(this._p.multiply(r))};Ft.prototype.add=function(t){return v0(this._p.add(t._p))};Ft.prototype.mulAdd=function(t,r,i){return this.mul(t).add(r.mul(i))};Ft.prototype.eq=function(t){return this._p.equals(t._p)};Ft.prototype.isInfinity=function(){return this._p.is0()};Ft.prototype.validate=function(){if(this.isInfinity())throw new Error("Point cannot be equal to Infinity");var t=this._p.toAffine();return CA(t.x,t.y),this};Ft.pointToCompressed=function(t){var r=t.getX().toBuffer({size:32}),i=t.getY().toBuffer({size:32}),n,o=i[i.length-1]%2;return o?n=h.Buffer.from([3]):n=h.Buffer.from([2]),h.Buffer.concat([n,r])};Ft.pointFromCompressed=function(e){if(e.length!==33)throw new Error("invalid buffer length");var t=e[0],r;if(t===3)r=!0;else if(t===2)r=!1;else throw new Error("invalid value of compressed prefix");var i=MA.fromBuffer(e.slice(1,33));return Ft.fromX(r,i)};Ft.prototype.toBuffer=function(){return Ft.pointToCompressed(this)};Ft.prototype.toHex=function(){return this.toBuffer().toString("hex")};Ft.fromBuffer=function(e){return Ft.pointFromCompressed(e)};Ft.fromHex=function(e){return Ft.fromBuffer(h.Buffer.from(e,"hex"))};DA.exports=Ft});var pi=k((S2e,UA)=>{"use strict";v();var qA=xt(),mX=Bt(),LA=function(t){return qA.isString(t)?/^[0-9a-fA-F]+$/.test(t):!1};UA.exports={isValidJSON:function(t){var r;if(!qA.isString(t))return!1;try{r=JSON.parse(t)}catch{return!1}return typeof r=="object"},isHexa:LA,isHexaString:LA,defineImmutable:function(t,r){return Object.keys(r).forEach(function(i){Object.defineProperty(t,i,{configurable:!1,enumerable:!0,value:r[i]})}),t},isNaturalNumber:function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t&&t>=0},integerAsBuffer:function(t){mX.checkArgumentType(t,"number","integer");let r=h.Buffer.allocUnsafe(4);return r.writeUInt32BE(t,0),r}}});var Vr=k((E2e,HA)=>{"use strict";v();var af=fr(),yX=xt(),_i=Bt(),bX=pi(),mt=function e(t,r){if(!(this instanceof e))return new e(t,r);if(t instanceof af)this.set({r:t,s:r});else if(t){var i=t;this.set(i)}};mt.prototype.set=function(e){return this.r=e.r||this.r||void 0,this.s=e.s||this.s||void 0,this.i=typeof e.i<"u"?e.i:this.i,this.compressed=typeof e.compressed<"u"?e.compressed:this.compressed,this.nhashtype=e.nhashtype||this.nhashtype||void 0,this};mt.fromCompact=function(e){_i.checkArgument(h.Buffer.isBuffer(e),"Argument is expected to be a Buffer");var t=new mt,r=!0,i=e.slice(0,1)[0]-27-4;i<0&&(r=!1,i=i+4);var n=e.slice(1,33),o=e.slice(33,65);return _i.checkArgument(i===0||i===1||i===2||i===3,new Error("i must be 0, 1, 2, or 3")),_i.checkArgument(n.length===32,new Error("r must be 32 bytes")),_i.checkArgument(o.length===32,new Error("s must be 32 bytes")),t.compressed=r,t.i=i,t.r=af.fromBuffer(n),t.s=af.fromBuffer(o),t};mt.fromDER=mt.fromBuffer=function(e,t){var r=mt.parseDER(e,t),i=new mt;return i.r=r.r,i.s=r.s,i};mt.fromTxFormat=function(e){var t=e.readUInt8(e.length-1),r=e.slice(0,e.length-1),i=mt.fromDER(r,!1);return i.nhashtype=t,i};mt.fromString=function(e){var t=h.Buffer.from(e,"hex");return mt.fromDER(t)};function FA(e,t){_i.checkArgument(t.length>0,new Error("Length of "+e+" is zero")),_i.checkArgument(!(t[0]&128),new Error("Value of "+e+" is negative")),_i.checkArgument(!(t.length>1&&t[0]===0&&!(t[1]&128)),new Error("Value of "+e+" is excessively padded"))}mt.parseDER=function(e,t){_i.checkArgument(h.Buffer.isBuffer(e),new Error("DER formatted signature should be a buffer")),yX.isUndefined(t)&&(t=!0);var r=e[0];_i.checkArgument(r===48,new Error("Header byte should be 0x30"));var i=e[1],n=e.slice(2).length;_i.checkArgument(!t||i===n,new Error("Length byte should length of what follows")),i=i<n?i:n;var o=e[2];_i.checkArgument(o===2,new Error("Integer byte for r should be 0x02"));var a=e[3],s=e.slice(4,4+a),u=af.fromBuffer(s),c=e[4]===0;_i.checkArgument(a===s.length,new Error("Length of r incorrect"));var l=e[4+a+0];_i.checkArgument(l===2,new Error("Integer byte for s should be 0x02"));var m=e[4+a+1],w=e.slice(4+a+2,4+a+2+m),E=af.fromBuffer(w),P=e[4+a+2]===0;_i.checkArgument(m===w.length,new Error("Length of s incorrect"));var M=4+a+2+m;_i.checkArgument(i===M-2,new Error("Length of signature incorrect")),t&&(FA("r",s),FA("s",w));var D={header:r,length:i,rheader:o,rlength:a,rneg:c,rbuf:s,r:u,sheader:l,slength:m,sneg:P,sbuf:w,s:E};return D};mt.prototype.toCompact=function(e,t){if(e=typeof e=="number"?e:this.i,t=typeof t=="boolean"?t:this.compressed,!(e===0||e===1||e===2||e===3))throw new Error("i must be equal to 0, 1, 2, or 3");var r=e+27+4;t===!1&&(r=r-4);var i=h.Buffer.from([r]),n=this.r.toBuffer({size:32}),o=this.s.toBuffer({size:32});return h.Buffer.concat([i,n,o])};mt.prototype.toBuffer=mt.prototype.toDER=function(){var e=this.r.toBuffer(),t=this.s.toBuffer(),r=!!(e[0]&128),i=!!(t[0]&128),n=r?h.Buffer.concat([h.Buffer.from([0]),e]):e,o=i?h.Buffer.concat([h.Buffer.from([0]),t]):t,a=n.length,s=o.length,u=2+a+2+s,c=2,l=2,m=48,w=h.Buffer.concat([h.Buffer.from([m,u,c,a]),n,h.Buffer.from([l,s]),o]);return w};mt.prototype.toString=function(){var e=this.toDER();return e.toString("hex")};mt.isTxDER=function(e){if(e.length<9||e.length>73||e[0]!==48||e[1]!==e.length-3)return!1;var t=e[3];if(5+t>=e.length)return!1;var r=e[5+t];if(t+r+7!==e.length)return!1;var i=e.slice(4);if(e[2]!==2||t===0||i[0]&128||t>1&&i[0]===0&&!(i[1]&128))return!1;var n=e.slice(6+t);return!(e[6+t-2]!==2||r===0||n[0]&128||r>1&&n[0]===0&&!(n[1]&128))};mt.prototype.hasLowS=function(){return!(this.s.lt(new af(1))||this.s.gt(new af("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))};mt.prototype.hasDefinedHashtype=function(){if(!bX.isNaturalNumber(this.nhashtype))return!1;var e=this.nhashtype&31;return!(e<mt.SIGHASH_ALL||e>mt.SIGHASH_SINGLE)};mt.prototype.toTxFormat=function(){var e=this.toDER(),t=h.Buffer.alloc(1);return t.writeUInt8(this.nhashtype,0),h.Buffer.concat([e,t])};mt.SIGHASH_ALL=1;mt.SIGHASH_NONE=2;mt.SIGHASH_SINGLE=3;mt.SIGHASH_FORKID=64;mt.SIGHASH_ANYONECANPAY=128;mt.prototype.isCanonical=function(){var e=vn(),t=e.getN().shrn(1);return this.s.lte(t)};mt.prototype.toCanonical=function(){if(this.isCanonical())return new mt({r:this.r,s:this.s,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype});var e=vn(),t=e.getN(),r=t.sub(this.s);return new mt({r:this.r,s:r,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype})};mt.prototype.validate=function(){if(!this.r||!this.s)throw new Error("Signature missing r or s component");if(this.r.isZero())throw new Error("Signature r component is zero");if(this.s.isZero())throw new Error("Signature s component is zero");var e=vn(),t=e.getN();if(this.r.gte(t))throw new Error("Signature r component >= curve order");if(this.s.gte(t))throw new Error("Signature s component >= curve order");if(this.r.isNeg())throw new Error("Signature r component is negative");if(this.s.isNeg())throw new Error("Signature s component is negative");return!0};mt.prototype.isValid=function(){try{return this.validate(),!0}catch{return!1}};mt.prototype.applySecurityPatches=function(){var e=vn(),t=e.getN(),r=t.shrn(1);if(this.r.isZero()||this.s.isZero())throw new Error("Invalid signature: zero r or s");if(this.r.gte(t)||this.s.gte(t))throw new Error("Invalid signature: out of range");if(this.s.gt(r))throw new Error("Invalid signature: non-canonical (high) s");return this};HA.exports=mt});var jn=k(Ht=>{"use strict";v();var _X=Rn(),wX=Ot();Ht.inherits=wX;function SX(e,t){return(e.charCodeAt(t)&64512)!==55296||t<0||t+1>=e.length?!1:(e.charCodeAt(t+1)&64512)===56320}function xX(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if(typeof e=="string")if(t){if(t==="hex")for(e=e.replace(/[^a-z0-9]+/ig,""),e.length%2!==0&&(e="0"+e),n=0;n<e.length;n+=2)r.push(parseInt(e[n]+e[n+1],16))}else for(var i=0,n=0;n<e.length;n++){var o=e.charCodeAt(n);o<128?r[i++]=o:o<2048?(r[i++]=o>>6|192,r[i++]=o&63|128):SX(e,n)?(o=65536+((o&1023)<<10)+(e.charCodeAt(++n)&1023),r[i++]=o>>18|240,r[i++]=o>>12&63|128,r[i++]=o>>6&63|128,r[i++]=o&63|128):(r[i++]=o>>12|224,r[i++]=o>>6&63|128,r[i++]=o&63|128)}else for(n=0;n<e.length;n++)r[n]=e[n]|0;return r}Ht.toArray=xX;function EX(e){for(var t="",r=0;r<e.length;r++)t+=zA(e[r].toString(16));return t}Ht.toHex=EX;function jA(e){var t=e>>>24|e>>>8&65280|e<<8&16711680|(e&255)<<24;return t>>>0}Ht.htonl=jA;function OX(e,t){for(var r="",i=0;i<e.length;i++){var n=e[i];t==="little"&&(n=jA(n)),r+=KA(n.toString(16))}return r}Ht.toHex32=OX;function zA(e){return e.length===1?"0"+e:e}Ht.zero2=zA;function KA(e){return e.length===7?"0"+e:e.length===6?"00"+e:e.length===5?"000"+e:e.length===4?"0000"+e:e.length===3?"00000"+e:e.length===2?"000000"+e:e.length===1?"0000000"+e:e}Ht.zero8=KA;function IX(e,t,r,i){var n=r-t;_X(n%4===0);for(var o=new Array(n/4),a=0,s=t;a<o.length;a++,s+=4){var u;i==="big"?u=e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3]:u=e[s+3]<<24|e[s+2]<<16|e[s+1]<<8|e[s],o[a]=u>>>0}return o}Ht.join32=IX;function AX(e,t){for(var r=new Array(e.length*4),i=0,n=0;i<e.length;i++,n+=4){var o=e[i];t==="big"?(r[n]=o>>>24,r[n+1]=o>>>16&255,r[n+2]=o>>>8&255,r[n+3]=o&255):(r[n+3]=o>>>24,r[n+2]=o>>>16&255,r[n+1]=o>>>8&255,r[n]=o&255)}return r}Ht.split32=AX;function PX(e,t){return e>>>t|e<<32-t}Ht.rotr32=PX;function TX(e,t){return e<<t|e>>>32-t}Ht.rotl32=TX;function kX(e,t){return e+t>>>0}Ht.sum32=kX;function RX(e,t,r){return e+t+r>>>0}Ht.sum32_3=RX;function BX(e,t,r,i){return e+t+r+i>>>0}Ht.sum32_4=BX;function MX(e,t,r,i,n){return e+t+r+i+n>>>0}Ht.sum32_5=MX;function NX(e,t,r,i){var n=e[t],o=e[t+1],a=i+o>>>0,s=(a<i?1:0)+r+n;e[t]=s>>>0,e[t+1]=a}Ht.sum64=NX;function CX(e,t,r,i){var n=t+i>>>0,o=(n<t?1:0)+e+r;return o>>>0}Ht.sum64_hi=CX;function DX(e,t,r,i){var n=t+i;return n>>>0}Ht.sum64_lo=DX;function LX(e,t,r,i,n,o,a,s){var u=0,c=t;c=c+i>>>0,u+=c<t?1:0,c=c+o>>>0,u+=c<o?1:0,c=c+s>>>0,u+=c<s?1:0;var l=e+r+n+a+u;return l>>>0}Ht.sum64_4_hi=LX;function qX(e,t,r,i,n,o,a,s){var u=t+i+o+s;return u>>>0}Ht.sum64_4_lo=qX;function UX(e,t,r,i,n,o,a,s,u,c){var l=0,m=t;m=m+i>>>0,l+=m<t?1:0,m=m+o>>>0,l+=m<o?1:0,m=m+s>>>0,l+=m<s?1:0,m=m+c>>>0,l+=m<c?1:0;var w=e+r+n+a+u+l;return w>>>0}Ht.sum64_5_hi=UX;function FX(e,t,r,i,n,o,a,s,u,c){var l=t+i+o+s+c;return l>>>0}Ht.sum64_5_lo=FX;function HX(e,t,r){var i=t<<32-r|e>>>r;return i>>>0}Ht.rotr64_hi=HX;function jX(e,t,r){var i=e<<32-r|t>>>r;return i>>>0}Ht.rotr64_lo=jX;function zX(e,t,r){return e>>>r}Ht.shr64_hi=zX;function KX(e,t,r){var i=e<<32-r|t>>>r;return i>>>0}Ht.shr64_lo=KX});var Yc=k(GA=>{"use strict";v();var VA=jn(),VX=Rn();function Op(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}GA.BlockHash=Op;Op.prototype.update=function(t,r){if(t=VA.toArray(t,r),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var i=t.length%this._delta8;this.pending=t.slice(t.length-i,t.length),this.pending.length===0&&(this.pending=null),t=VA.join32(t,0,t.length-i,this.endian);for(var n=0;n<t.length;n+=this._delta32)this._update(t,n,n+this._delta32)}return this};Op.prototype.digest=function(t){return this.update(this._pad()),VX(this.pending===null),this._digest(t)};Op.prototype._pad=function(){var t=this.pendingTotal,r=this._delta8,i=r-(t+this.padLength)%r,n=new Array(i+this.padLength);n[0]=128;for(var o=1;o<i;o++)n[o]=0;if(t<<=3,this.endian==="big"){for(var a=8;a<this.padLength;a++)n[o++]=0;n[o++]=0,n[o++]=0,n[o++]=0,n[o++]=0,n[o++]=t>>>24&255,n[o++]=t>>>16&255,n[o++]=t>>>8&255,n[o++]=t&255}else for(n[o++]=t&255,n[o++]=t>>>8&255,n[o++]=t>>>16&255,n[o++]=t>>>24&255,n[o++]=0,n[o++]=0,n[o++]=0,n[o++]=0,a=8;a<this.padLength;a++)n[o++]=0;return n}});var Ey=k(Pa=>{"use strict";v();var GX=jn(),Po=GX.rotr32;function ZX(e,t,r,i){if(e===0)return ZA(t,r,i);if(e===1||e===3)return YA(t,r,i);if(e===2)return WA(t,r,i)}Pa.ft_1=ZX;function ZA(e,t,r){return e&t^~e&r}Pa.ch32=ZA;function WA(e,t,r){return e&t^e&r^t&r}Pa.maj32=WA;function YA(e,t,r){return e^t^r}Pa.p32=YA;function WX(e){return Po(e,2)^Po(e,13)^Po(e,22)}Pa.s0_256=WX;function YX(e){return Po(e,6)^Po(e,11)^Po(e,25)}Pa.s1_256=YX;function $X(e){return Po(e,7)^Po(e,18)^e>>>3}Pa.g0_256=$X;function XX(e){return Po(e,17)^Po(e,19)^e>>>10}Pa.g1_256=XX});var JA=k((B2e,XA)=>{"use strict";v();var $c=jn(),JX=Yc(),QX=Ey(),Oy=$c.rotl32,y0=$c.sum32,eJ=$c.sum32_5,tJ=QX.ft_1,$A=JX.BlockHash,rJ=[1518500249,1859775393,2400959708,3395469782];function To(){if(!(this instanceof To))return new To;$A.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}$c.inherits(To,$A);XA.exports=To;To.blockSize=512;To.outSize=160;To.hmacStrength=80;To.padLength=64;To.prototype._update=function(t,r){for(var i=this.W,n=0;n<16;n++)i[n]=t[r+n];for(;n<i.length;n++)i[n]=Oy(i[n-3]^i[n-8]^i[n-14]^i[n-16],1);var o=this.h[0],a=this.h[1],s=this.h[2],u=this.h[3],c=this.h[4];for(n=0;n<i.length;n++){var l=~~(n/20),m=eJ(Oy(o,5),tJ(l,a,s,u),c,i[n],rJ[l]);c=u,u=s,s=Oy(a,30),a=o,o=m}this.h[0]=y0(this.h[0],o),this.h[1]=y0(this.h[1],a),this.h[2]=y0(this.h[2],s),this.h[3]=y0(this.h[3],u),this.h[4]=y0(this.h[4],c)};To.prototype._digest=function(t){return t==="hex"?$c.toHex32(this.h,"big"):$c.split32(this.h,"big")}});var Iy=k((N2e,eP)=>{"use strict";v();var Xc=jn(),iJ=Yc(),Jc=Ey(),nJ=Rn(),zn=Xc.sum32,oJ=Xc.sum32_4,aJ=Xc.sum32_5,sJ=Jc.ch32,uJ=Jc.maj32,fJ=Jc.s0_256,cJ=Jc.s1_256,lJ=Jc.g0_256,hJ=Jc.g1_256,QA=iJ.BlockHash,dJ=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ko(){if(!(this instanceof ko))return new ko;QA.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=dJ,this.W=new Array(64)}Xc.inherits(ko,QA);eP.exports=ko;ko.blockSize=512;ko.outSize=256;ko.hmacStrength=192;ko.padLength=64;ko.prototype._update=function(t,r){for(var i=this.W,n=0;n<16;n++)i[n]=t[r+n];for(;n<i.length;n++)i[n]=oJ(hJ(i[n-2]),i[n-7],lJ(i[n-15]),i[n-16]);var o=this.h[0],a=this.h[1],s=this.h[2],u=this.h[3],c=this.h[4],l=this.h[5],m=this.h[6],w=this.h[7];for(nJ(this.k.length===i.length),n=0;n<i.length;n++){var E=aJ(w,cJ(c),sJ(c,l,m),this.k[n],i[n]),P=zn(fJ(o),uJ(o,a,s));w=m,m=l,l=c,c=zn(u,E),u=s,s=a,a=o,o=zn(E,P)}this.h[0]=zn(this.h[0],o),this.h[1]=zn(this.h[1],a),this.h[2]=zn(this.h[2],s),this.h[3]=zn(this.h[3],u),this.h[4]=zn(this.h[4],c),this.h[5]=zn(this.h[5],l),this.h[6]=zn(this.h[6],m),this.h[7]=zn(this.h[7],w)};ko.prototype._digest=function(t){return t==="hex"?Xc.toHex32(this.h,"big"):Xc.split32(this.h,"big")}});var iP=k((D2e,rP)=>{"use strict";v();var Ay=jn(),tP=Iy();function Ta(){if(!(this instanceof Ta))return new Ta;tP.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Ay.inherits(Ta,tP);rP.exports=Ta;Ta.blockSize=512;Ta.outSize=224;Ta.hmacStrength=192;Ta.padLength=64;Ta.prototype._digest=function(t){return t==="hex"?Ay.toHex32(this.h.slice(0,7),"big"):Ay.split32(this.h.slice(0,7),"big")}});var ky=k((q2e,sP)=>{"use strict";v();var Ri=jn(),pJ=Yc(),gJ=Rn(),Ro=Ri.rotr64_hi,Bo=Ri.rotr64_lo,nP=Ri.shr64_hi,oP=Ri.shr64_lo,_s=Ri.sum64,Py=Ri.sum64_hi,Ty=Ri.sum64_lo,vJ=Ri.sum64_4_hi,mJ=Ri.sum64_4_lo,yJ=Ri.sum64_5_hi,bJ=Ri.sum64_5_lo,aP=pJ.BlockHash,_J=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Kn(){if(!(this instanceof Kn))return new Kn;aP.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=_J,this.W=new Array(160)}Ri.inherits(Kn,aP);sP.exports=Kn;Kn.blockSize=1024;Kn.outSize=512;Kn.hmacStrength=192;Kn.padLength=128;Kn.prototype._prepareBlock=function(t,r){for(var i=this.W,n=0;n<32;n++)i[n]=t[r+n];for(;n<i.length;n+=2){var o=RJ(i[n-4],i[n-3]),a=BJ(i[n-4],i[n-3]),s=i[n-14],u=i[n-13],c=TJ(i[n-30],i[n-29]),l=kJ(i[n-30],i[n-29]),m=i[n-32],w=i[n-31];i[n]=vJ(o,a,s,u,c,l,m,w),i[n+1]=mJ(o,a,s,u,c,l,m,w)}};Kn.prototype._update=function(t,r){this._prepareBlock(t,r);var i=this.W,n=this.h[0],o=this.h[1],a=this.h[2],s=this.h[3],u=this.h[4],c=this.h[5],l=this.h[6],m=this.h[7],w=this.h[8],E=this.h[9],P=this.h[10],M=this.h[11],D=this.h[12],L=this.h[13],U=this.h[14],K=this.h[15];gJ(this.k.length===i.length);for(var N=0;N<i.length;N+=2){var C=U,F=K,H=AJ(w,E),z=PJ(w,E),G=wJ(w,E,P,M,D,L),B=SJ(w,E,P,M,D,L),g=this.k[N],O=this.k[N+1],y=i[N],f=i[N+1],d=yJ(C,F,H,z,G,B,g,O,y,f),_=bJ(C,F,H,z,G,B,g,O,y,f);C=OJ(n,o),F=IJ(n,o),H=xJ(n,o,a,s,u,c),z=EJ(n,o,a,s,u,c);var x=Py(C,F,H,z),b=Ty(C,F,H,z);U=D,K=L,D=P,L=M,P=w,M=E,w=Py(l,m,d,_),E=Ty(m,m,d,_),l=u,m=c,u=a,c=s,a=n,s=o,n=Py(d,_,x,b),o=Ty(d,_,x,b)}_s(this.h,0,n,o),_s(this.h,2,a,s),_s(this.h,4,u,c),_s(this.h,6,l,m),_s(this.h,8,w,E),_s(this.h,10,P,M),_s(this.h,12,D,L),_s(this.h,14,U,K)};Kn.prototype._digest=function(t){return t==="hex"?Ri.toHex32(this.h,"big"):Ri.split32(this.h,"big")};function wJ(e,t,r,i,n){var o=e&r^~e&n;return o<0&&(o+=4294967296),o}function SJ(e,t,r,i,n,o){var a=t&i^~t&o;return a<0&&(a+=4294967296),a}function xJ(e,t,r,i,n){var o=e&r^e&n^r&n;return o<0&&(o+=4294967296),o}function EJ(e,t,r,i,n,o){var a=t&i^t&o^i&o;return a<0&&(a+=4294967296),a}function OJ(e,t){var r=Ro(e,t,28),i=Ro(t,e,2),n=Ro(t,e,7),o=r^i^n;return o<0&&(o+=4294967296),o}function IJ(e,t){var r=Bo(e,t,28),i=Bo(t,e,2),n=Bo(t,e,7),o=r^i^n;return o<0&&(o+=4294967296),o}function AJ(e,t){var r=Ro(e,t,14),i=Ro(e,t,18),n=Ro(t,e,9),o=r^i^n;return o<0&&(o+=4294967296),o}function PJ(e,t){var r=Bo(e,t,14),i=Bo(e,t,18),n=Bo(t,e,9),o=r^i^n;return o<0&&(o+=4294967296),o}function TJ(e,t){var r=Ro(e,t,1),i=Ro(e,t,8),n=nP(e,t,7),o=r^i^n;return o<0&&(o+=4294967296),o}function kJ(e,t){var r=Bo(e,t,1),i=Bo(e,t,8),n=oP(e,t,7),o=r^i^n;return o<0&&(o+=4294967296),o}function RJ(e,t){var r=Ro(e,t,19),i=Ro(t,e,29),n=nP(e,t,6),o=r^i^n;return o<0&&(o+=4294967296),o}function BJ(e,t){var r=Bo(e,t,19),i=Bo(t,e,29),n=oP(e,t,6),o=r^i^n;return o<0&&(o+=4294967296),o}});var cP=k((F2e,fP)=>{"use strict";v();var Ry=jn(),uP=ky();function ka(){if(!(this instanceof ka))return new ka;uP.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}Ry.inherits(ka,uP);fP.exports=ka;ka.blockSize=1024;ka.outSize=384;ka.hmacStrength=192;ka.padLength=128;ka.prototype._digest=function(t){return t==="hex"?Ry.toHex32(this.h.slice(0,12),"big"):Ry.split32(this.h.slice(0,12),"big")}});var lP=k(Qc=>{"use strict";v();Qc.sha1=JA();Qc.sha224=iP();Qc.sha256=Iy();Qc.sha384=cP();Qc.sha512=ky()});var mP=k(vP=>{"use strict";v();var sf=jn(),MJ=Yc(),Ip=sf.rotl32,hP=sf.sum32,b0=sf.sum32_3,dP=sf.sum32_4,gP=MJ.BlockHash;function Mo(){if(!(this instanceof Mo))return new Mo;gP.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}sf.inherits(Mo,gP);vP.ripemd160=Mo;Mo.blockSize=512;Mo.outSize=160;Mo.hmacStrength=192;Mo.padLength=64;Mo.prototype._update=function(t,r){for(var i=this.h[0],n=this.h[1],o=this.h[2],a=this.h[3],s=this.h[4],u=i,c=n,l=o,m=a,w=s,E=0;E<80;E++){var P=hP(Ip(dP(i,pP(E,n,o,a),t[DJ[E]+r],NJ(E)),qJ[E]),s);i=s,s=a,a=Ip(o,10),o=n,n=P,P=hP(Ip(dP(u,pP(79-E,c,l,m),t[LJ[E]+r],CJ(E)),UJ[E]),w),u=w,w=m,m=Ip(l,10),l=c,c=P}P=b0(this.h[1],o,m),this.h[1]=b0(this.h[2],a,w),this.h[2]=b0(this.h[3],s,u),this.h[3]=b0(this.h[4],i,c),this.h[4]=b0(this.h[0],n,l),this.h[0]=P};Mo.prototype._digest=function(t){return t==="hex"?sf.toHex32(this.h,"little"):sf.split32(this.h,"little")};function pP(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}function NJ(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function CJ(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}var DJ=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],LJ=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],qJ=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],UJ=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]});var bP=k((G2e,yP)=>{"use strict";v();var FJ=jn(),HJ=Rn();function el(e,t,r){if(!(this instanceof el))return new el(e,t,r);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(FJ.toArray(t,r))}yP.exports=el;el.prototype._init=function(t){t.length>this.blockSize&&(t=new this.Hash().update(t).digest()),HJ(t.length<=this.blockSize);for(var r=t.length;r<this.blockSize;r++)t.push(0);for(r=0;r<t.length;r++)t[r]^=54;for(this.inner=new this.Hash().update(t),r=0;r<t.length;r++)t[r]^=106;this.outer=new this.Hash().update(t)};el.prototype.update=function(t,r){return this.inner.update(t,r),this};el.prototype.digest=function(t){return this.outer.update(this.inner.digest()),this.outer.digest(t)}});var wP=k(_P=>{v();var ri=_P;ri.utils=jn();ri.common=Yc();ri.sha=lP();ri.ripemd=mP();ri.hmac=bP();ri.sha1=ri.sha.sha1;ri.sha256=ri.sha.sha256;ri.sha224=ri.sha.sha224;ri.sha384=ri.sha.sha384;ri.sha512=ri.sha.sha512;ri.ripemd160=ri.ripemd.ripemd160});var xP=k(($2e,SP)=>{"use strict";v();var Ap=wP(),Ra=Bt(),Sr=SP.exports;Sr.sha1=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),h.Buffer.from(Ap.sha1().update(e).digest("hex"),"hex")};Sr.sha1.blocksize=512;Sr.sha256=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),h.Buffer.from(Ap.sha256().update(e).digest("hex"),"hex")};Sr.sha256.blocksize=512;Sr.sha256sha256=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),Sr.sha256(Sr.sha256(e))};Sr.ripemd160=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),h.Buffer.from(Ap.ripemd160().update(e).digest("hex"),"hex")};Sr.sha256ripemd160=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),Sr.ripemd160(Sr.sha256(e))};Sr.sha512=function(e){return Ra.checkArgument(h.Buffer.isBuffer(e)),h.Buffer.from(Ap.sha512().update(e).digest("hex"),"hex")};Sr.sha512.blocksize=1024;Sr.hmac=function(e,t,r){Ra.checkArgument(h.Buffer.isBuffer(t)),Ra.checkArgument(h.Buffer.isBuffer(r)),Ra.checkArgument(e.blocksize);var i=e.blocksize/8;if(r.length>i)r=e(r);else if(r<i){var n=h.Buffer.alloc(i);n.fill(0),r.copy(n),r=n}var o=h.Buffer.alloc(i);o.fill(92);var a=h.Buffer.alloc(i);a.fill(54);for(var s=h.Buffer.alloc(i),u=h.Buffer.alloc(i),c=0;c<i;c++)s[c]=o[c]^r[c],u[c]=a[c]^r[c];return e(h.Buffer.concat([s,e(h.Buffer.concat([u,t]))]))};Sr.sha256hmac=function(e,t){return Sr.hmac(Sr.sha256,e,t)};Sr.sha512hmac=function(e,t){return Sr.hmac(Sr.sha512,e,t)}});var OP=k((J2e,EP)=>{"use strict";v();var Pp=_r(),Ba=Bt(),xr=EP.exports;xr.sha1=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),Pp.createHash("sha1").update(e).digest()};xr.sha1.blocksize=512;xr.sha256=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),Pp.createHash("sha256").update(e).digest()};xr.sha256.blocksize=512;xr.sha256sha256=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),xr.sha256(xr.sha256(e))};xr.ripemd160=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),Pp.createHash("ripemd160").update(e).digest()};xr.sha256ripemd160=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),xr.ripemd160(xr.sha256(e))};xr.sha512=function(e){return Ba.checkArgument(h.Buffer.isBuffer(e)),Pp.createHash("sha512").update(e).digest()};xr.sha512.blocksize=1024;xr.hmac=function(e,t,r){Ba.checkArgument(h.Buffer.isBuffer(t)),Ba.checkArgument(h.Buffer.isBuffer(r)),Ba.checkArgument(e.blocksize);var i=e.blocksize/8;if(r.length>i)r=e(r);else if(r<i){var n=h.Buffer.alloc(i);n.fill(0),r.copy(n),r=n}var o=h.Buffer.alloc(i);o.fill(92);var a=h.Buffer.alloc(i);a.fill(54);for(var s=h.Buffer.alloc(i),u=h.Buffer.alloc(i),c=0;c<i;c++)s[c]=o[c]^r[c],u[c]=a[c]^r[c];return e(h.Buffer.concat([s,e(h.Buffer.concat([u,t]))]))};xr.sha256hmac=function(e,t){return xr.hmac(xr.sha256,e,t)};xr.sha512hmac=function(e,t){return xr.hmac(xr.sha512,e,t)}});var cr=k((epe,By)=>{v();A.default.browser?By.exports=xP():By.exports=OP()});var Ss=k((rpe,PP)=>{"use strict";v();var Ma=xt(),_0=pi(),uf=[],w0={};function IP(){}IP.prototype.toString=function(){return this.name};function S0(e,t){if(~uf.indexOf(e))return e;if(t){Ma.isArray(t)||(t=[t]);for(var r=0;r<uf.length;r++){var i=uf[r],n=Ma.pick(i,t),o=Ma.values(n);if(~o.indexOf(e))return i}return}return w0[e]}function Ny(e){for(var t=[],r=0;r<e.length;r++)t.push(e.charCodeAt(r)&31);return t}function x0(e){var t=new IP;_0.defineImmutable(t,{name:e.name,alias:e.alias,pubkeyhash:e.pubkeyhash,privatekey:e.privatekey,scripthash:e.scripthash,xpubkey:e.xpubkey,xprivkey:e.xprivkey});var r=e.indexBy||Object.keys(e);return e.cashAddrPrefix&&Ma.extend(t,{cashAddrPrefix:e.cashAddrPrefix,cashAddrPrefixArray:Ny(e.cashAddrPrefix)}),e.networkMagic&&Ma.extend(t,{networkMagic:_0.integerAsBuffer(e.networkMagic)}),e.port&&Ma.extend(t,{port:e.port}),e.dnsSeeds&&Ma.extend(t,{dnsSeeds:e.dnsSeeds}),uf.push(t),jJ(t,r),t}function jJ(e,t){for(var r=0;r<t.length;r++){var i=t[r],n=e[i];!Ma.isUndefined(n)&&!Ma.isObject(n)&&(w0[n]=e)}}function zJ(e,t){for(var r=0;r<t.length;r++){var i=t[r];w0[i]===e&&delete w0[i]}}function KJ(e){for(var t=0;t<uf.length;t++)uf[t]===e&&uf.splice(t,1);zJ(e,Object.keys(w0))}var Tp={livenet:3823236072,testnet:4108710900,regtest:3669344250,stn:4224632057},AP=["seed.bitcoinsv.org","seed.bitcoinunlimited.info"],ws={PORT:18333,NETWORK_MAGIC:Tp.testnet,DNS_SEEDS:AP,PREFIX:"testnet",CASHADDRPREFIX:"bchtest"},Na={PORT:18444,NETWORK_MAGIC:Tp.regtest,DNS_SEEDS:[],PREFIX:"regtest",CASHADDRPREFIX:"bchreg"},Ca={PORT:9333,NETWORK_MAGIC:Tp.stn,DNS_SEEDS:["stn-seed.bitcoinsv.io"],PREFIX:"stn",CASHADDRPREFIX:"bsvstn"},VJ={name:"livenet",alias:"mainnet",prefix:"bitcoin",cashAddrPrefix:"bitcoincash",pubkeyhash:0,privatekey:128,scripthash:5,xpubkey:76067358,xprivkey:76066276,networkMagic:Tp.livenet,port:8333,dnsSeeds:AP},GJ={name:"testnet",prefix:ws.PREFIX,cashAddrPrefix:ws.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:ws.NETWORK_MAGIC},ZJ={name:"regtest",prefix:Na.PREFIX,cashAddrPrefix:Na.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:Na.NETWORK_MAGIC,port:Na.PORT,dnsSeeds:[],indexBy:["port","name","cashAddrPrefix","networkMagic"]},WJ={name:"stn",prefix:Ca.PREFIX,cashAddrPrefix:Ca.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:Ca.NETWORK_MAGIC,indexBy:["port","name","cashAddrPrefix","networkMagic"]};x0(GJ);x0(WJ);x0(ZJ);x0(VJ);var My=S0("livenet"),YJ=S0("regtest"),No=S0("testnet"),$J=S0("stn");Object.defineProperty(No,"port",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?Na.PORT:this.stnEnabled?Ca.PORT:ws.PORT}});Object.defineProperty(No,"networkMagic",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?_0.integerAsBuffer(Na.NETWORK_MAGIC):this.stnEnabled?_0.integerAsBuffer(Ca.NETWORK_MAGIC):_0.integerAsBuffer(ws.NETWORK_MAGIC)}});Object.defineProperty(No,"dnsSeeds",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?Na.DNS_SEEDS:this.stnEnabled?Ca.DNS_SEEDS:ws.DNS_SEEDS}});Object.defineProperty(No,"cashAddrPrefix",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?Na.CASHADDRPREFIX:this.stnEnabled?Ca.CASHADDRPREFIX:ws.CASHADDRPREFIX}});Object.defineProperty(No,"cashAddrPrefixArray",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?Ny(Na.CASHADDRPREFIX):this.stnEnabled?Ca.cashAddrPrefixToArray(Ca.CASHADDRPREFIX):Ny(ws.CASHADDRPREFIX)}});function XJ(){No.regtestEnabled=!0}function JJ(){No.regtestEnabled=!1}function QJ(){No.stnEnabled=!0}function eQ(){No.stnEnabled=!1}PP.exports={add:x0,remove:KJ,defaultNetwork:My,livenet:My,mainnet:My,testnet:No,regtest:YJ,stn:$J,get:S0,enableRegtest:XJ,disableRegtest:JJ,enableStn:QJ,disableStn:eQ}});var E0=k((npe,RP)=>{"use strict";v();var Cy=xt(),TP=Y2(),kP=Kt(),tQ="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split(""),Gr=function e(t){if(!(this instanceof e))return new e(t);if(h.Buffer.isBuffer(t)){var r=t;this.fromBuffer(r)}else if(typeof t=="string"){var i=t;this.fromString(i)}};Gr.validCharacters=function(t){return kP.Buffer.isBuffer(t)&&(t=t.toString()),Cy.every(Cy.map(t,function(r){return Cy.includes(tQ,r)}))};Gr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this};Gr.encode=function(e){if(!kP.Buffer.isBuffer(e))throw new Error("Input should be a buffer");return TP.encode(e)};Gr.decode=function(e){if(typeof e!="string")throw new Error("Input should be a string");return h.Buffer.from(TP.decode(e))};Gr.prototype.fromBuffer=function(e){return this.buf=e,this};Gr.fromBuffer=function(e){return new Gr().fromBuffer(e)};Gr.fromHex=function(e){return Gr.fromBuffer(h.Buffer.from(e,"hex"))};Gr.prototype.fromString=function(e){var t=Gr.decode(e);return this.buf=t,this};Gr.fromString=function(e){return new Gr().fromString(e)};Gr.prototype.toBuffer=function(){return this.buf};Gr.prototype.toHex=function(){return this.toBuffer().toString("hex")};Gr.prototype.toString=function(){return Gr.encode(this.buf)};RP.exports=Gr});var tl=k((ape,CP)=>{"use strict";v();var BP=xt(),kp=E0(),MP=Kt(),NP=cr().sha256sha256,lr=function e(t){if(!(this instanceof e))return new e(t);if(h.Buffer.isBuffer(t)){var r=t;this.fromBuffer(r)}else if(typeof t=="string"){var i=t;this.fromString(i)}};lr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this};lr.validChecksum=function(t,r){return BP.isString(t)&&(t=MP.Buffer.from(kp.decode(t))),BP.isString(r)&&(r=MP.Buffer.from(kp.decode(r))),r||(r=t.slice(-4),t=t.slice(0,-4)),lr.checksum(t).toString("hex")===r.toString("hex")};lr.decode=function(e){if(typeof e!="string")throw new Error("Input must be a string");var t=h.Buffer.from(kp.decode(e));if(t.length<4)throw new Error("Input string too short");var r=t.slice(0,-4),i=t.slice(-4),n=NP(r),o=n.slice(0,4);if(i.toString("hex")!==o.toString("hex"))throw new Error("Checksum mismatch");return r};lr.checksum=function(e){return NP(e).slice(0,4)};lr.encode=function(e){if(!h.Buffer.isBuffer(e))throw new Error("Input must be a buffer");var t=h.Buffer.alloc(e.length+4),r=lr.checksum(e);return e.copy(t),r.copy(t,e.length),kp.encode(t)};lr.prototype.fromBuffer=function(e){return this.buf=e,this};lr.fromBuffer=function(e){return new lr().fromBuffer(e)};lr.fromHex=function(e){return lr.fromBuffer(h.Buffer.from(e,"hex"))};lr.prototype.fromString=function(e){var t=lr.decode(e);return this.buf=t,this};lr.fromString=function(e){var t=lr.decode(e);return new lr(t)};lr.prototype.toBuffer=function(){return this.buf};lr.prototype.toHex=function(){return this.toBuffer().toString("hex")};lr.prototype.toString=function(){return lr.encode(this.buf)};CP.exports=lr});var Da=k((upe,LP)=>{"use strict";v();var O0=xt(),DP=Bt(),rl=fr(),gr=function e(t){if(!(this instanceof e))return new e(t);if(!O0.isUndefined(t))if(h.Buffer.isBuffer(t))this.set({buf:t});else if(O0.isString(t)){var r=h.Buffer.from(t,"hex");if(r.length*2!==t.length)throw new TypeError("Invalid hex string");this.set({buf:r})}else if(O0.isObject(t)){var i=t;this.set(i)}else throw new TypeError("Unrecognized argument for BufferReader")};gr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this.pos=e.pos||this.pos||0,this};gr.prototype.eof=function(){return this.pos>=this.buf.length};gr.prototype.finished=gr.prototype.eof;gr.prototype.read=function(e){DP.checkArgument(!O0.isUndefined(e),"Must specify a length");var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,t};gr.prototype.readAll=function(){var e=this.buf.slice(this.pos,this.buf.length);return this.pos=this.buf.length,e};gr.prototype.readUInt8=function(){var e=this.buf.readUInt8(this.pos);return this.pos=this.pos+1,e};gr.prototype.readUInt16BE=function(){var e=this.buf.readUInt16BE(this.pos);return this.pos=this.pos+2,e};gr.prototype.readUInt16LE=function(){var e=this.buf.readUInt16LE(this.pos);return this.pos=this.pos+2,e};gr.prototype.readUInt32BE=function(){var e=this.buf.readUInt32BE(this.pos);return this.pos=this.pos+4,e};gr.prototype.readUInt32LE=function(){var e=this.buf.readUInt32LE(this.pos);return this.pos=this.pos+4,e};gr.prototype.readInt32LE=function(){var e=this.buf.readInt32LE(this.pos);return this.pos=this.pos+4,e};gr.prototype.readUInt64BEBN=function(){var e=this.buf.slice(this.pos,this.pos+8),t=rl.fromBuffer(e);return this.pos=this.pos+8,t};gr.prototype.readUInt64LEBN=function(){var e=this.buf.readUInt32LE(this.pos),t=this.buf.readUInt32LE(this.pos+4),r=t*4294967296+e,i;if(r<=9007199254740991)i=new rl(r);else{var n=Array.prototype.slice.call(this.buf,this.pos,this.pos+8);i=new rl(n,10,"le")}return this.pos=this.pos+8,i};gr.prototype.readVarintNum=function(){var e=this.readUInt8();switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:var t=this.readUInt64LEBN(),r=t.toNumber();if(r<=Math.pow(2,53))return r;throw new Error("number too large to retain precision - use readVarintBN");default:return e}};gr.prototype.readVarLengthBuffer=function(){var e=this.readVarintNum(),t=this.read(e);return DP.checkState(t.length===e,"Invalid length while reading varlength buffer. Expected to read: "+e+" and read "+t.length),t};gr.prototype.readVarintBuf=function(){var e=this.buf.readUInt8(this.pos);switch(e){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}};gr.prototype.readVarintBN=function(){var e=this.readUInt8();switch(e){case 253:return new rl(this.readUInt16LE());case 254:return new rl(this.readUInt32LE());case 255:return this.readUInt64LEBN();default:return new rl(e)}};gr.prototype.reverse=function(){for(var e=h.Buffer.alloc(this.buf.length),t=0;t<e.length;t++)e[t]=this.buf[this.buf.length-1-t];return this.buf=e,this};gr.prototype.readReverse=function(e){O0.isUndefined(e)&&(e=this.buf.length);var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,h.Buffer.from(t).reverse()};LP.exports=gr});var qy=k((cpe,HP)=>{"use strict";v();function xs(e){"@babel/helpers - typeof";return xs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xs(e)}function qP(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,iQ(i.key),i)}}function rQ(e,t,r){return t&&qP(e.prototype,t),r&&qP(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function iQ(e){var t=nQ(e,"string");return xs(t)==="symbol"?t:String(t)}function nQ(e,t){if(xs(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(xs(i)!=="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function oQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function aQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ly(e,t)}function Ly(e,t){return Ly=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Ly(e,t)}function sQ(e){var t=cQ();return function(){var i=Rp(e),n;if(t){var o=Rp(this).constructor;n=Reflect.construct(i,arguments,o)}else n=i.apply(this,arguments);return uQ(this,n)}}function uQ(e,t){if(t&&(xs(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return fQ(e)}function fQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function cQ(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Rp(e){return Rp=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Rp(e)}var FP={},il,Dy;function I0(e,t,r){r||(r=Error);function i(o,a,s){return typeof t=="string"?t:t(o,a,s)}var n=(function(o){aQ(s,o);var a=sQ(s);function s(u,c,l){var m;return oQ(this,s),m=a.call(this,i(u,c,l)),m.code=e,m}return rQ(s)})(r);FP[e]=n}function UP(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(i){return String(i)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function lQ(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function hQ(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function dQ(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}I0("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError);I0("ERR_INVALID_ARG_TYPE",function(e,t,r){il===void 0&&(il=Es()),il(typeof e=="string","'name' must be a string");var i;typeof t=="string"&&lQ(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be";var n;if(hQ(e," argument"))n="The ".concat(e," ").concat(i," ").concat(UP(t,"type"));else{var o=dQ(e,".")?"property":"argument";n='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(UP(t,"type"))}return n+=". Received type ".concat(xs(r)),n},TypeError);I0("ERR_INVALID_ARG_VALUE",function(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid";Dy===void 0&&(Dy=rn());var i=Dy.inspect(t);return i.length>128&&(i="".concat(i.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(r,". Received ").concat(i)},TypeError,RangeError);I0("ERR_INVALID_RETURN_VALUE",function(e,t,r){var i;return r&&r.constructor&&r.constructor.name?i="instance of ".concat(r.constructor.name):i="type ".concat(xs(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(i,".")},TypeError);I0("ERR_MISSING_ARGS",function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];il===void 0&&(il=Es()),il(t.length>0,"At least one arg needs to be specified");var i="The ",n=t.length;switch(t=t.map(function(o){return'"'.concat(o,'"')}),n){case 1:i+="".concat(t[0]," argument");break;case 2:i+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:i+=t.slice(0,n-1).join(", "),i+=", and ".concat(t[n-1]," arguments");break}return"".concat(i," must be specified")},TypeError);HP.exports.codes=FP});var XP=k((hpe,$P)=>{"use strict";v();function jP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,i)}return r}function zP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?jP(Object(r),!0).forEach(function(i){pQ(e,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jP(Object(r)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(r,i))})}return e}function pQ(e,t,r){return t=ZP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function KP(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,ZP(i.key),i)}}function vQ(e,t,r){return t&&KP(e.prototype,t),r&&KP(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function ZP(e){var t=mQ(e,"string");return Bi(t)==="symbol"?t:String(t)}function mQ(e,t){if(Bi(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(Bi(i)!=="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function yQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&k0(e,t)}function bQ(e){var t=YP();return function(){var i=R0(e),n;if(t){var o=R0(this).constructor;n=Reflect.construct(i,arguments,o)}else n=i.apply(this,arguments);return WP(this,n)}}function WP(e,t){if(t&&(Bi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Uy(e)}function Uy(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Fy(e){var t=typeof Map=="function"?new Map:void 0;return Fy=function(i){if(i===null||!_Q(i))return i;if(typeof i!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(i))return t.get(i);t.set(i,n)}function n(){return Bp(i,arguments,R0(this).constructor)}return n.prototype=Object.create(i.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),k0(n,i)},Fy(e)}function Bp(e,t,r){return YP()?Bp=Reflect.construct.bind():Bp=function(n,o,a){var s=[null];s.push.apply(s,o);var u=Function.bind.apply(n,s),c=new u;return a&&k0(c,a.prototype),c},Bp.apply(null,arguments)}function YP(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function _Q(e){return Function.toString.call(e).indexOf("[native code]")!==-1}function k0(e,t){return k0=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},k0(e,t)}function R0(e){return R0=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},R0(e)}function Bi(e){"@babel/helpers - typeof";return Bi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bi(e)}var wQ=rn(),Hy=wQ.inspect,SQ=qy(),xQ=SQ.codes.ERR_INVALID_ARG_TYPE;function VP(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function EQ(e,t){if(t=Math.floor(t),e.length==0||t==0)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+=e.substring(0,r-e.length),e}var Vn="",A0="",P0="",ii="",ff={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},OQ=10;function GP(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach(function(i){r[i]=e[i]}),Object.defineProperty(r,"message",{value:e.message}),r}function T0(e){return Hy(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function IQ(e,t,r){var i="",n="",o=0,a="",s=!1,u=T0(e),c=u.split(`
20
20
  `),l=T0(t).split(`
@@ -94,10 +94,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
94
94
  [${a+1}/${n.length}] Step (${u}) \u2014 press Enter to execute...`,c)):r&&console.log(`
95
95
  [${a+1}/${n.length}] Step (${u})`);try{if(typeof i.step=="function")i.step();else{console.log("\u26A0\uFE0F Step-by-step execution not supported in this BSV version"),console.log("\u{1F4A1} Consider using runFullEvaluation instead");break}console.log(`\u{1F9E9} Executed: ${u}`),R8(i.stack,i.altstack)}catch(c){console.log(`\u26A0\uFE0F Error executing ${u}: ${c.message}`);break}}o&&o.close(),console.log(`
96
96
  ===========================================`),console.log("\u2705 Final Stack State:"),R8(i.stack||[],i.altstack||[]),console.log("===========================================")}function LN(e,t,r){console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (FULL RUN)"),console.log(`===========================================
97
- `);let i=new Lr.Script.Interpreter,n=new Lr.crypto.BN(1e5),o=i.verify(e,t,r,0,Lr.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(a=>a.toString("hex"))),console.log("AltStack:",i.altstack.map(a=>a.toString("hex"))),console.log("===========================================")}async function qN(){if(typeof A.default>"u"||!A.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=A.default.argv.slice(2),t=w=>{let E=e.indexOf(w);return E!==-1&&e[E+1]?e[E+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),a=e.includes("--truth"),s,u,c;if(n)c=q6(n);else{s=q6(r),u=q6(i);let w=h.Buffer.concat([s.toBuffer(),u.toBuffer()]);c=Lr.Script.fromBuffer(w)}let l=new Lr.Transaction,m=new Lr.Transaction.Input({prevTxId:"0".repeat(64),outputIndex:0,script:Lr.Script.empty(),satoshis:1e5,output:new Lr.Transaction.Output({satoshis:1e5,script:Lr.Script.empty()})});l.addInput(m),l.addOutput(new Lr.Transaction.Output({satoshis:1e5,script:Lr.Script.empty()})),o?await DN(c,l,!0):a?LN(s||Lr.Script.empty(),u||Lr.Script.empty(),l):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}B8.exports={parseScript:q6,printStack:R8,stepThroughScript:DN,runFullEvaluation:LN,main:qN};typeof Fr<"u"&&Fr.main===B8&&qN()});var Go=k(($ge,zN)=>{"use strict";v();var vi=Te(),F6=fr(),lne=cr(),FN=Vr(),M8=FN.SIGHASH_ALL|FN.SIGHASH_FORKID;function HN(){var e=vi.Script.Interpreter;return e.SCRIPT_VERIFY_P2SH|e.SCRIPT_VERIFY_STRICTENC|e.SCRIPT_VERIFY_DERSIG|e.SCRIPT_VERIFY_LOW_S|e.SCRIPT_VERIFY_MINIMALDATA|e.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY|e.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY|e.SCRIPT_ENABLE_SIGHASH_FORKID|e.SCRIPT_ENABLE_MAGNETIC_OPCODES|e.SCRIPT_ENABLE_MONOLITH_OPCODES}function hne(e){return vi.Script.Interpreter.useGenesisLimits(e)}function dne(e,t,r){r=r||{};var i=new vi.Script.Interpreter,n=i.verify(e,t,r.tx||new vi.Transaction,r.inputIndex||0,r.flags||HN(),new F6(r.satoshis||0));return{ok:n,err:i.errstr||""}}function jN(e,t,r,i,n){return vi.Transaction.sighash.sighashPreimage(e,n||M8,t,r,new F6(i))}function pne(e,t,r,i,n){return lne.sha256sha256(jN(e,t,r,i,n))}function gne(e,t,r,i,n,o){o=o||M8;var a=vi.Transaction.sighash.sign(e,t,o,r,i,new F6(n));return h.Buffer.concat([a.toDER(),h.Buffer.from([o])])}function vne(e,t,r){r=r||{};var i=new vi.Transaction().addOutput(new vi.Transaction.Output({script:e,satoshis:t})),n=new vi.Transaction;return n.addInput(new vi.Transaction.Input({prevTxId:i.hash,outputIndex:0,script:vi.Script.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function mne(e,t){var r=e.toAddress?e.toAddress():e;return new vi.Transaction.Output({script:vi.Script.buildPublicKeyHashOut(r),satoshis:t})}function yne(e){return e===0?vi.Opcode.OP_0:e===-1?vi.Opcode.OP_1NEGATE:e>=1&&e<=16?vi.Opcode["OP_"+e]:new F6(e).toScriptNumBuffer()}zN.exports={SIGHASH:M8,flags:HN,enableGenesis:hne,verify:dne,rawPreimage:jN,sighashDigest:pne,signInput:gne,fundAndSpend:vne,p2pkhOutput:mne,scriptNum:yne}});var YN=k((Jge,WN)=>{"use strict";v();var KN=Te(),VN=cr(),GN=Go(),ao=KN.Script,Ar=KN.Opcode,b1=GN.signInput,ZN=GN.scriptNum;function bne(e){var t=VN.sha256(e),r=new ao().add(Ar.OP_SHA256).add(t).add(Ar.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new ao().add(o||e)}}}function _ne(e){var t=e.toPublicKey(),r=ao.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new ao().add(b1(i,e,0,r,n)).add(t.toBuffer())}}}function wne(e,t){var r=e.toPublicKey(),i=new ao().add(ZN(t)).add(Ar.OP_CHECKLOCKTIMEVERIFY).add(Ar.OP_DROP).add(r.toBuffer()).add(Ar.OP_CHECKSIG);return{lock:i,meta:{name:"cltv-timelock",locktime:t},unlock:function(n,o){return new ao().add(b1(n,e,0,i,o))}}}function Sne(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new ao().add(Ar["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ar["OP_"+r.length]).add(Ar.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,a){a=a||t.slice(0,e);var s=new ao().add(Ar.OP_0);return a.forEach(function(u){s.add(b1(n,u,0,i,o))}),s}}}function xne(e){var t=VN.sha256(e.secret),r=new ao().add(Ar.OP_IF).add(Ar.OP_SHA256).add(t).add(Ar.OP_EQUALVERIFY).add(e.receiver.toPublicKey().toBuffer()).add(Ar.OP_CHECKSIG).add(Ar.OP_ELSE).add(ZN(e.timeout)).add(Ar.OP_CHECKLOCKTIMEVERIFY).add(Ar.OP_DROP).add(e.sender.toPublicKey().toBuffer()).add(Ar.OP_CHECKSIG).add(Ar.OP_ENDIF);return{lock:r,meta:{name:"htlc",digest:t.toString("hex"),timeout:e.timeout},unlockClaim:function(i,n){return new ao().add(b1(i,e.receiver,0,r,n)).add(e.secret).add(Ar.OP_1)},unlockRefund:function(i,n){return new ao().add(b1(i,e.sender,0,r,n)).add(Ar.OP_0)}}}WN.exports={hashLock:bne,p2pkh:_ne,timeLockCLTV:wne,multisig:Sne,htlc:xne}});var Tl=k((eve,iC)=>{"use strict";v();var C8=Te(),H6=fr(),$N=cr(),D8=Go(),XN=C8.Script,Nt=C8.Opcode,L8=D8.SIGHASH,j6=D8.scriptNum,Pl=h.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),q8=new H6("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Ene=h.Buffer.concat([h.Buffer.from([2]),Pl]),JN=h.Buffer.from(Pl).reverse(),QN=h.Buffer.concat([h.Buffer.from(q8.toBuffer()).reverse(),h.Buffer.from([0])]),One=h.Buffer.concat([h.Buffer.from([48,68,2,32]),Pl,h.Buffer.from([2,32])]);function N8(e,t){var r;for(r=0;r<t-1;r++)e.add(Nt.OP_1).add(Nt.OP_SPLIT);for(r=0;r<t-1;r++)e.add(Nt.OP_SWAP).add(Nt.OP_CAT);return e}var Zo=C8.crypto.Signature,Ine=Zo.SIGHASH_ALL|Zo.SIGHASH_FORKID,Ane=Zo.SIGHASH_SINGLE|Zo.SIGHASH_FORKID,Pne=Zo.SIGHASH_SINGLE|Zo.SIGHASH_ANYONECANPAY|Zo.SIGHASH_FORKID,Tne=Zo.SIGHASH_ALL|Zo.SIGHASH_ANYONECANPAY|Zo.SIGHASH_FORKID;function U8(e,t){var r=t&&t.sighashType||L8;return e.add(Nt.OP_HASH256),N8(e,32),e.add(JN).add(Nt.OP_ADD),e.add(QN).add(Nt.OP_MOD),e.add(j6(32)).add(Nt.OP_NUM2BIN),N8(e,32),e.add(Pl).add(Nt.OP_DUP),e.add(Nt.OP_2).add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(Nt.OP_TOALTSTACK),e.add(h.Buffer.from([48,68,2,32])).add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(h.Buffer.from([2,32])).add(Nt.OP_CAT),e.add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(h.Buffer.from([r])).add(Nt.OP_CAT),e.add(Nt.OP_FROMALTSTACK).add(Nt.OP_CHECKSIG),e}function kne(){return U8(new XN)}function eC(e){return e.add(j6(40)).add(Nt.OP_RIGHT).add(j6(32)).add(Nt.OP_LEFT),e}function Rne(e){return tC(e,L8)}function tC(e,t){var r=h.Buffer.from([t&255,0,0,0]);return e.add(Nt.OP_DUP).add(j6(4)).add(Nt.OP_RIGHT).add(r).add(Nt.OP_EQUALVERIFY),e}function Bne(e){var t=h.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return $N.sha256sha256(t)}function Mne(e){var t=new XN().add(Nt.OP_DUP);return U8(t),t.add(Nt.OP_VERIFY),eC(t),t.add(h.Buffer.from(e)).add(Nt.OP_EQUAL),t}var Nne=new H6("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function rC(e){var t=$N.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new H6(t).add(new H6(Pl)).mod(q8);if(r.gt(Nne))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function Cne(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,a=n.start||0,s=n.field||"nLockTime",u=n.sighashType||L8;if(s!=="nLockTime"&&s!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var c=e.inputs[t],l=0;l<o;l++){var m=a+l;s==="nLockTime"?e.nLockTime=m:c.sequenceNumber=4294967294-m;var w=D8.rawPreimage(e,t,r,i,u);if(rC(w))return{preimage:w,tries:l+1,field:s,nonce:m}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}iC.exports={Gx:Pl,N:q8,PUBKEY:Ene,gxLe:JN,N_LE:QN,DER_PREFIX:One,reverseBytes:N8,pushTxCore:U8,authenticator:kne,extractHashOutputs:eC,assertSighashAll:Rne,assertSighashType:tC,SIGHASH_ALL_FORKID:Ine,SIGHASH_SINGLE_FORKID:Ane,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Pne,SIGHASH_ALL_ANYONECANPAY_FORKID:Tne,hashOutputs:Bne,valueCovenant:Mne,sFromPreimage:rC,grind:Cne}});var H8=k((rve,oC)=>{"use strict";v();var nC=Te(),F8=Tl(),Dne=Go(),Lne=nC.Script,Pr=nC.Opcode,kl=Dne.scriptNum;function qne(e){var t=new Lne;return t.add(Pr.OP_DUP),F8.pushTxCore(t),t.add(Pr.OP_VERIFY),F8.assertSighashAll(t),t.add(Pr.OP_DUP),t.add(kl(104)).add(Pr.OP_SPLIT).add(Pr.OP_NIP),t.add(Pr.OP_SIZE).add(kl(52)).add(Pr.OP_SUB).add(Pr.OP_SPLIT).add(Pr.OP_DROP),t.add(Pr.OP_OVER),t.add(kl(52)).add(Pr.OP_RIGHT).add(kl(8)).add(Pr.OP_LEFT),t.add(Pr.OP_BIN2NUM).add(kl(e)).add(Pr.OP_SUB),t.add(kl(8)).add(Pr.OP_NUM2BIN),t.add(Pr.OP_SWAP).add(Pr.OP_CAT),t.add(Pr.OP_HASH256),t.add(Pr.OP_SWAP),F8.extractHashOutputs(t),t.add(Pr.OP_EQUAL),t}oC.exports={pelsCovenant:qne}});var K8=k((nve,sC)=>{"use strict";v();var K6=Te(),aC=cr(),z8=Go(),$t=K6.Opcode,Rl=z8.scriptNum;function z6(e){return e instanceof K6.PrivateKey?e.toPublicKey().toBuffer():e instanceof K6.PublicKey?e.toBuffer():e}function Une(){return{name:"single-key",commit:function(e){return aC.sha256ripemd160(z6(e))},emit:function(e){return e.add($t.OP_OVER).add($t.OP_HASH160).add($t.OP_EQUALVERIFY),e.add($t.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=z8.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function j8(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new K6.Script().add($t["OP_"+e]);return t.forEach(function(n){i.add(h.Buffer.from(n))}),i.add($t["OP_"+r]).add($t.OP_CHECKMULTISIG),i.toBuffer()}function Fne(e,t){if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return aC.sha256ripemd160(j8(e,r.map(z6)))},emit:function(r){r.add($t.OP_OVER).add($t.OP_HASH160).add($t.OP_EQUALVERIFY),r.add(Rl(1)).add($t.OP_SPLIT).add($t.OP_NIP),r.add($t.OP_SIZE).add(Rl(2)).add($t.OP_SUB).add($t.OP_SPLIT).add($t.OP_DROP);for(var i=0;i<this.n;i++)r.add(Rl(34)).add($t.OP_SPLIT),r.add($t.OP_SWAP).add(Rl(1)).add($t.OP_SPLIT).add($t.OP_NIP),r.add($t.OP_TOALTSTACK);for(r.add($t.OP_DROP),r.add(Rl(this.m)),i=0;i<this.n;i++)r.add($t.OP_FROMALTSTACK);return r.add(Rl(this.n)),r.add($t.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,a){var s=a.keys;if(s.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var u=j8(e,s.map(z6)),c=s.map(z6).map(function(w){return w.toString("hex")}),l=a.signWith.map(function(w){var E=c.indexOf(w.toPublicKey().toBuffer().toString("hex"));if(E<0)throw new Error("signWith key is not in the committed key set");return{idx:E,priv:w}}).sort(function(w,E){return E.idx-w.idx}).slice(0,e);if(l.length<e)throw new Error("need at least "+e+" signing keys");var m=l.map(function(w){return z8.signInput(r,w.priv,i,n,o)});return[$t.OP_0].concat(m).concat([u])}}}function Hne(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}sC.exports={singleKey:Une,multisig:Fne,predicate:Hne,redeemScript:j8}});var Z8=k((ave,gC)=>{"use strict";v();var V8=Te(),_1=Tl(),G8=Go(),w1=K8(),V6=V8.Script,Ie=V8.Opcode,Wo=G8.scriptNum;function fC(e,t){var r=h.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function uC(e,t){return t.length?e.add(h.Buffer.from(t)):e.add(Ie.OP_0)}function cC(e,t){return e.add(Ie.OP_DUP),_1.pushTxCore(e),e.add(Ie.OP_VERIFY),_1.assertSighashAll(e),e.add(Ie.OP_DUP).add(Wo(52)).add(Ie.OP_RIGHT).add(Wo(8)).add(Ie.OP_LEFT).add(Ie.OP_TOALTSTACK),e.add(Ie.OP_DUP),_1.extractHashOutputs(e),e.add(Ie.OP_TOALTSTACK),e.add(Wo(104)).add(Ie.OP_SPLIT).add(Ie.OP_NIP).add(Ie.OP_SIZE).add(Wo(52)).add(Ie.OP_SUB).add(Ie.OP_SPLIT).add(Ie.OP_DROP),e.add(Ie.OP_DUP).add(Wo(4)).add(Wo(20)).add(Ie.OP_SUBSTR),e.add(Ie.OP_SWAP).add(Ie.OP_TOALTSTACK),t.emit(e),e.add(Ie.OP_FROMALTSTACK),e}function lC(e){return e.add(Wo(4)).add(Ie.OP_SPLIT).add(Wo(20)).add(Ie.OP_SPLIT).add(Ie.OP_NIP),e.add(Ie.OP_TOALTSTACK),e.add(Ie.OP_SWAP).add(Ie.OP_CAT),e.add(Ie.OP_FROMALTSTACK).add(Ie.OP_CAT),e}function hC(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function jne(e,t,r){r=r||w1.singleKey();var i=new V6;return i.add(fC(t,r)),i.add(Ie.OP_DROP),cC(i,r),lC(i),i.add(Ie.OP_FROMALTSTACK),i.add(Ie.OP_SWAP),i.add(Ie.OP_FROMALTSTACK),i.add(Ie.OP_BIN2NUM).add(Wo(e)).add(Ie.OP_SUB).add(Wo(8)).add(Ie.OP_NUM2BIN),i.add(Ie.OP_SWAP).add(Ie.OP_CAT),i.add(Ie.OP_HASH256),i.add(Ie.OP_EQUAL),hC(i)}function dC(e,t){t=t||w1.singleKey();var r=new V6;return r.add(fC(e,t)),r.add(Ie.OP_DROP),cC(r,t),lC(r),r.add(Ie.OP_CAT),r.add(Ie.OP_SWAP).add(Ie.OP_CAT),r.add(Ie.OP_CAT),r.add(Ie.OP_FROMALTSTACK),r.add(Ie.OP_FROMALTSTACK).add(Ie.OP_DROP),r.add(Ie.OP_SWAP).add(Ie.OP_HASH256).add(Ie.OP_EQUAL),hC(r)}function zne(e){return w1.singleKey().commit(e)}function Kne(e,t,r,i,n,o){o=o||{};var a=o.auth||w1.singleKey(),s=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");_1.grind(r,s,n,i,o.grind);var u=G8.rawPreimage(r,s,n,i),c=a.unlockArgs(r,s,n,i,e),l=new V6().add(h.Buffer.from(t));return c.forEach(function(m){l.add(m)}),l.add(h.Buffer.from(u)),l}function pC(e,t,r,i,n,o,a){a=a||{};var s=a.auth||w1.singleKey(),u=a.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");_1.grind(r,u,n,i,a.grind);var c=G8.rawPreimage(r,u,n,i),l=s.unlockArgs(r,u,n,i,e),m=new V6;return uC(m,o.before||h.Buffer.alloc(0)),uC(m,o.after||h.Buffer.alloc(0)),m.add(h.Buffer.from(o.tokenValue)),m.add(h.Buffer.from(t)),l.forEach(function(w){m.add(w)}),m.add(h.Buffer.from(c)),m}function Vne(e,t){return dC(e,t)}function Gne(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var a=o.tokenIndex||0,s=r.outputs||[],u=s[a];if(!u)throw new Error("transferOrdinal: spend has no output at tokenIndex "+a);if(u.satoshis!==i)throw new Error("transferOrdinal: token output value ("+u.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function c(E){return E.toBufferWriter().toBuffer()}var l=h.Buffer.concat(s.slice(0,a).map(c)),m=h.Buffer.concat(s.slice(a+1).map(c)),w=new V8.crypto.BN(i).toBuffer({endian:"little",size:8});return pC(e,t,r,i,n,{before:l,after:m,tokenValue:w},o)}gC.exports={ownershipToken:jne,ownershipTokenMulti:dC,ordinalLock:Vne,ownerId:zne,unlockTransfer:Kne,unlockTransferMulti:pC,transferOrdinal:Gne}});var e7=k((uve,vC)=>{"use strict";v();var X8=Te(),G6=Tl(),Zne=H8(),Wne=Z8(),J8=Go(),Y8=X8.Script,xn=X8.Opcode,$8=X8.Transaction,W8=J8.scriptNum;function Yne(e,t){return e instanceof $8.Output?e:e instanceof Y8?new $8.Output({script:e,satoshis:t}):J8.p2pkhOutput(e,t)}function $ne(e,t,r,i,n,o){o=o||5e4;for(var a=0;a<o;a++){e.nLockTime=n+a;var s=J8.rawPreimage(e,t,r,i);if(G6.sFromPreimage(s))return s}throw new Error("covenant grind failed after "+o+" tries")}function $a(){if(!(this instanceof $a))return new $a;this._outputs=[],this._minLockTime=null}$a.prototype.payTo=function(e,t){return this._outputs.push(Yne(e,t)),this};$a.prototype.lockUntil=function(e){return this._minLockTime=e,this};$a.prototype.outputs=function(){return this._outputs.map(function(e){return new $8.Output(e.toObject())})};$a.prototype.describe=function(){var e=[];return this._outputs.forEach(function(t,r){e.push("output["+r+"] = "+t.satoshis+" sat to "+t.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null&&e.push("nLockTime >= "+this._minLockTime),"spend allowed iff: "+e.join(" AND ")};$a.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new Y8().add(xn.OP_DUP);if(G6.pushTxCore(t),t.add(xn.OP_VERIFY),this._outputs.length){var r=G6.hashOutputs(this._outputs);t.add(xn.OP_DUP),G6.extractHashOutputs(t),t.add(h.Buffer.from(r)).add(xn.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add(xn.OP_DUP),t.add(W8(8)).add(xn.OP_RIGHT).add(W8(4)).add(xn.OP_LEFT),t.add(xn.OP_BIN2NUM).add(W8(this._minLockTime)).add(xn.OP_GREATERTHANOREQUAL).add(xn.OP_VERIFY)),t.add(xn.OP_DROP).add(xn.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var a=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new Y8().add($ne(i,o,t,n,a))}}};function Q8(){return new $a}Q8.perpetual=function(e){return Zne.pelsCovenant(e)};Q8.token=function(e,t){return Wne.ownershipToken(e,t)};vC.exports={policy:Q8,Policy:$a}});var wC=k((cve,_C)=>{"use strict";v();var Z6=Te(),Xne=Go();function yC(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return Z6.Opcode.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function mC(e,t){t=t||16;var r=h.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function Jne(e,t,r){r=r||{};var i=new Z6.Script.Interpreter,n=[];i.stepListener=function(a,s,u){n.push({phase:i.script===t?"lock":"unlock",op:yC(a.opcode&&typeof a.opcode.toNumber=="function"?a.opcode.toNumber():a.opcode.num),stack:s.map(function(c){return mC(c)}),altstack:u.map(function(c){return mC(c)})})};var o=i.verify(e,t,r.tx||new Z6.Transaction,r.inputIndex||0,typeof r.flags=="number"?r.flags:Xne.flags(),new Z6.crypto.BN(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function bC(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",a=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+a)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
98
- `)}function Qne(e){return console.log(bC(e)),e}_C.exports={trace:Jne,format:bC,print:Qne,opLabel:yC}});var xC=k((hve,SC)=>{"use strict";v();var S1=Te(),ie={Covenant:cN(),Preimage:Vo(),SIGHASH:dN(),Builder:gN(),UTXOGenerator:EN(),ScriptTester:IN(),CovenantBuilder:I8().CovenantBuilder,CovenantTemplates:I8().CovenantTemplates,OpcodeMap:x8(),ScriptUtils:MN(),StackExaminer:CN(),ScriptInterpreter:UN(),CovenantHelpers:Go(),Locks:YN(),PushTx:Tl(),PELS:H8(),Token:Z8(),Authorizers:K8(),DSL:e7(),Policy:e7().Policy,Debugger:wC()};ie.policy=ie.DSL.policy;ie.trace=function(e,t,r){return ie.Debugger.trace(e,t,r)};ie.enableGenesis=function(e){return ie.CovenantHelpers.enableGenesis(e)};ie.verifyScript=function(e,t,r){return ie.CovenantHelpers.verify(e,t,r)};ie.perpetualCovenant=function(e){return ie.PELS.pelsCovenant(e)};ie.ownershipToken=function(e,t){return ie.Token.ownershipToken(e,t)};ie.valueCovenant=function(e){return ie.PushTx.valueCovenant(e)};ie.ordinalLock=function(e,t){return ie.Token.ordinalLock(e,t)};ie.transferOrdinal=function(e,t,r,i,n,o){return ie.Token.transferOrdinal(e,t,r,i,n,o)};ie.createCovenant=function(e,t){return new ie.Covenant(e,t)};ie.extractPreimage=function(e,t){return new ie.Preimage(e,t)};ie.analyzeSIGHASH=function(e){return new ie.SIGHASH(e)};ie.buildCovenant=function(e,t){return new ie.Builder(e,t)};ie.createUTXOGenerator=function(e){return new ie.UTXOGenerator(e)};ie.createTestEnvironment=function(e){return ie.UTXOGenerator.createTestEnvironment(e)};ie.testScript=function(e,t,r){return ie.ScriptTester.test(e,t,r)};ie.testCovenant=function(e,t,r){return ie.ScriptTester.testCovenant(e,t,r)};ie.testFieldExtraction=function(e,t,r){return ie.ScriptTester.testFieldExtraction(e,t,r)};ie.debugScript=function(e,t){var r=new ie.ScriptTester(t);return r.debug(e)};ie.explainZeroHashes=function(){return ie.SIGHASH.explainZeroMystery()};ie.getAllSIGHASHTypes=function(){return ie.SIGHASH.getAllTypes()};ie.demonstrateAllSIGHASH=function(){return ie.SIGHASH.generateAllDemonstrations()};ie.createCovenantBuilder=function(){return new ie.CovenantBuilder};ie.createValueLockCovenant=function(e){return ie.CovenantTemplates.valueLock(e)};ie.createHashLockCovenant=function(e){return ie.CovenantTemplates.hashLock(e)};ie.createComplexValidationCovenant=function(e){return ie.CovenantTemplates.complexValidation(e)};ie.getOpcodeMap=function(){return ie.OpcodeMap.opcodeMap};ie.simulateScript=function(e,t){return ie.OpcodeMap.utils.simulate(e,t)};ie.createASMFromJS=function(e){return ie.OpcodeMap.utils.createASM(e)};ie.scriptToASM=function(e){return ie.ScriptUtils.scriptToASM(e)};ie.asmToScript=function(e){return ie.ScriptUtils.asmToScript(e)};ie.asmToHex=function(e){return ie.ScriptUtils.asmToHex(e)};ie.hexToASM=function(e){return ie.ScriptUtils.hexToASM(e)};ie.scriptToHex=function(e){return ie.ScriptUtils.scriptToHex(e)};ie.validateASM=function(e){return ie.ScriptUtils.validateASM(e)};ie.validateScript=function(e){return ie.ScriptUtils.validateScript(e)};ie.estimateScriptSize=function(e){return ie.ScriptUtils.estimateScriptSize(e)};ie.optimizeScript=function(e){return ie.ScriptUtils.optimizeScript(e)};ie.compareScripts=function(e,t){return ie.ScriptUtils.compareScripts(e,t)};ie.explainScript=function(e){return ie.ScriptUtils.explainScript(e)};ie.scriptMetrics=function(e){return ie.ScriptUtils.scriptMetrics(e)};ie.analyzeComplexity=function(e){return ie.ScriptUtils.analyzeComplexity(e)};ie.findOptimizations=function(e){return ie.ScriptUtils.findOptimizations(e)};ie.covenantToEnglish=function(e){return ie.ScriptUtils.covenantToEnglish(e)};ie.batchTestScripts=function(e,t){return ie.ScriptUtils.batchTestScripts(e,t)};ie.examineStack=function(e,t){return ie.StackExaminer.runScript(e,t)};ie.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?ie.ScriptInterpreter.stepThroughScript(ie.ScriptInterpreter.parseScript(e+" "+t),new S1.Transaction,!0):ie.ScriptInterpreter.runFullEvaluation(ie.ScriptInterpreter.parseScript(e),ie.ScriptInterpreter.parseScript(t),new S1.Transaction)};ie.parseScript=function(e){return ie.ScriptInterpreter.parseScript(e)};ie.printStack=function(e,t){return ie.ScriptInterpreter.printStack(e,t)};ie.createQuickCovenant=function(e,t){let r=ie.createCovenantBuilder();switch(e){case"value_lock":return r.comment(`Value lock: minimum ${t.value} satoshis`).extractField("value").push(t.value).greaterThanOrEqual().verify().build();case"hash_lock":return r.comment(`Hash lock: requires preimage of ${t.hash}`).push("secret_placeholder").sha256().push(t.hash).equalVerify().build();case"time_lock":return r.comment(`Time lock: requires nLockTime > ${t.timestamp}`).extractField("nLockTime").push(t.timestamp).greaterThan().verify().build();case"multi_condition":let i=r.comment("Multi-condition covenant");return t.conditions.forEach(n=>{switch(n.type){case"value":i=i.extractField("value").push(n.value).greaterThanOrEqual().verify();break;case"hash":i=i.push("secret_placeholder").sha256().push(n.hash).equalVerify();break;case"time":i=i.extractField("nLockTime").push(n.timestamp).greaterThan().verify();break}}),i.build();default:throw new Error(`Unknown covenant type: ${e}`)}};ie.completeCovenantFlow=function(e,t,r){var i=new ie.Covenant(e);return i.completeFlow(t,r)};ie.getEducationalResources=function(){return{zeroHashMystery:ie.SIGHASH.explainZeroMystery(),sighashTypes:ie.SIGHASH.getAllTypes(),exampleDemonstrations:ie.SIGHASH.generateAllDemonstrations()}};ie.utils={};ie.utils.reconstructP2pkhScript=function(e){return S1.Script.buildPublicKeyHashOut(e).toHex()};ie.utils.createCovenantAddress=function(e){var t=S1.crypto.Hash.sha256ripemd160(e.toBuffer());return S1.Address.fromScriptHash(t)};ie.utils.decodeCompactSize=function(e,t){return ie.Preimage.decodeCompactSize(e,t)};ie.version=Km();ie.description="Smart Contract Framework for Bitcoin SV";ie.features={BIP143_PREIMAGE:!0,COMPACT_SIZE_VARINT:!0,BIDIRECTIONAL_EXTRACTION:!0,SIGHASH_DETECTION:!0,ZERO_HASH_WARNINGS:!0,MULTI_FIELD_VALIDATION:!0,REAL_UTXO_GENERATION:!0,SCRIPT_TESTING:!0,LOCAL_VERIFICATION:!0,JAVASCRIPT_TO_SCRIPT:!0,OPCODE_MAPPING:!0,COVENANT_BUILDER:!0,SCRIPT_ANALYSIS:!0,SCRIPT_OPTIMIZATION:!0,SCRIPT_CONVERSION:!0,BATCH_TESTING:!0,QUICK_COVENANTS:!0,SCRIPT_EXPLANATIONS:!0,STACK_EXAMINATION:!0,SCRIPT_DEBUGGING:!0,STEP_BY_STEP_EXECUTION:!0,INTERACTIVE_DEBUGGING:!0};ie.interpretScript=ie.debugScriptExecution;ie.getScriptMetrics=ie.scriptMetrics;SC.exports=ie});var EC=k((pve,x1)=>{"use strict";v();var W6=function(){var e=typeof A.default<"u"&&A.default.env&&A.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)},Xa={MEMORY:"memory",SESSION:"session",LOCAL:"local"};function xi(e){e=e||{},this.options={storage:e.storage||Xa.MEMORY,storageKey:e.storageKey||"smartledger-utxos",autoSave:e.autoSave!==!1,maxUTXOs:e.maxUTXOs||1e3};var t=[Xa.MEMORY,Xa.SESSION,Xa.LOCAL];if(t.indexOf(this.options.storage)===-1)throw new Error("Invalid storage type: "+this.options.storage);this.utxos=new Map,this.addressIndex=new Map,this.spentUTXOs=new Map,this.metadata={totalUTXOs:0,totalValue:0,createdAt:new Date().toISOString(),lastModified:new Date().toISOString()},this.loadFromStorage()}xi.prototype.getStorage=function(){return this.options.storage===Xa.SESSION?typeof sessionStorage<"u"?sessionStorage:null:this.options.storage===Xa.LOCAL&&typeof localStorage<"u"?localStorage:null};xi.prototype.loadFromStorage=function(){var e=this.getStorage();if(e)try{var t=e.getItem(this.options.storageKey);if(!t)return;var r=JSON.parse(t);if(!r.utxos)return;var i=this;r.utxos.forEach(function(n){var o=n.txid+":"+n.vout;i.utxos.set(o,n),i.addressIndex.has(n.address)||i.addressIndex.set(n.address,new Set),i.addressIndex.get(n.address).add(o)}),r.metadata&&(this.metadata=r.metadata),W6("\u2705 BrowserUTXOManager: Loaded "+this.utxos.size+" UTXOs from "+this.options.storage+" storage")}catch(n){console.error("Failed to load UTXOs from storage:",n)}};xi.prototype.saveToStorage=function(){if(this.options.storage!==Xa.MEMORY){var e=this.getStorage();if(e)try{var t={utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",timestamp:new Date().toISOString()};e.setItem(this.options.storageKey,JSON.stringify(t)),W6("\u{1F4BE} BrowserUTXOManager: Saved "+this.utxos.size+" UTXOs to "+this.options.storage+" storage")}catch(r){console.error("Failed to save UTXOs to storage:",r)}}};xi.prototype.addUTXO=function(e){if(!e||!e.txid||typeof e.vout!="number")throw new Error("Invalid UTXO: missing txid or vout");var t=e.txid+":"+e.vout;if(this.utxos.has(t))return W6("\u26A0\uFE0F UTXO already exists: "+t),!1;var r={txid:e.txid,vout:e.vout,address:e.address||"",satoshis:e.satoshis||0,script:e.script||"",status:"available",addedAt:new Date().toISOString()};return this.utxos.set(t,r),r.address&&(this.addressIndex.has(r.address)||this.addressIndex.set(r.address,new Set),this.addressIndex.get(r.address).add(t)),this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),!0};xi.prototype.getUTXOsForAddress=function(e){var t=this.addressIndex.get(e);if(!t)return[];var r=[],i=this;return t.forEach(function(n){var o=i.utxos.get(n);o&&o.status==="available"&&r.push(o)}),r};xi.prototype.getBalance=function(e){var t=this.getUTXOsForAddress(e);return t.reduce(function(r,i){return r+(i.satoshis||0)},0)};xi.prototype.spendUTXOs=function(e,t){t=t||"browser-spend";for(var r=[],i=0;i<e.length;i++){var n=e[i],o=n.txid+":"+n.vout,a=this.utxos.get(o);a&&a.status==="available"&&(a.status="spent",a.spentAt=new Date().toISOString(),a.spentInTx=t,this.spentUTXOs.set(o,{txid:a.txid,vout:a.vout,spentInTx:t,spentAt:a.spentAt}),r.push(a))}return this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),r};xi.prototype.getUTXO=function(e,t){var r=e+":"+t,i=this.utxos.get(r);return{exists:!!i,utxo:i,status:i?i.status:"not-found"}};xi.prototype.createMockUTXOs=function(e,t,r){t=t||5,r=r||1e5;for(var i=[],n=0;n<t;n++){for(var o="",a=0;a<64;a++)o+=Math.floor(Math.random()*16).toString(16);var s={txid:o,vout:n,address:e,satoshis:r+Math.floor(Math.random()*1e4),script:"",status:"available"};this.addUTXO(s),i.push(s)}return i};xi.prototype.getStats=function(){var e=0,t=0,r=0;return this.utxos.forEach(function(i){e+=i.satoshis||0,i.status==="available"?t++:i.status==="spent"&&r++}),{totalUTXOs:this.utxos.size,totalAvailable:t,totalSpent:r,totalValue:e,totalAddresses:this.addressIndex.size,storageType:this.options.storage,metadata:this.metadata}};xi.prototype.updateMetadata=function(){var e=this.getStats();this.metadata.totalUTXOs=e.totalUTXOs,this.metadata.totalValue=e.totalValue,this.metadata.lastModified=new Date().toISOString()};xi.prototype.exportData=function(){return JSON.stringify({utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",exportedAt:new Date().toISOString()})};xi.prototype.importData=function(e,t){t=t||!1;try{var r=JSON.parse(e);if(t||(this.utxos.clear(),this.addressIndex.clear(),this.spentUTXOs.clear()),r.utxos&&Array.isArray(r.utxos)){var i=this;r.utxos.forEach(function(n){i.addUTXO(n)})}return W6("\u2705 BrowserUTXOManager: Imported "+(r.utxos&&r.utxos.length||0)+" UTXOs"),!0}catch(n){return console.error("Failed to import UTXO data:",n),!1}};typeof x1<"u"&&x1.exports?(x1.exports=xi,x1.exports.STORAGE_TYPES=Xa):typeof window<"u"&&(window.BrowserUTXOManager=xi,window.BrowserUTXOManager.STORAGE_TYPES=Xa)});var IC=k((vve,OC)=>{"use strict";v();var t7=class{constructor(t,r={}){this.bsv=t,this.options={difficulty:r.difficulty||1,blockTime:r.blockTime||1e4,validateScripts:r.validateScripts!==!1,logLevel:r.logLevel||"info",...r},this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[]}acceptTransaction(t){try{return this.options.validateScripts&&!this.validateTransactionSignatures(t)?(this.log("warn","\u274C Transaction rejected: Invalid signatures"),!1):(this.mempool.push(t),this.log("info",`\u2705 Transaction accepted into mempool: ${t.id||"unknown"}`),!0)}catch(r){return this.log("error",`\u274C Transaction rejected: ${r.message}`),!1}}validateTransactionSignatures(t){try{let r=t.verify();return this.log("debug",`\u{1F4CA} Transaction verification result: ${r}`),r===!0}catch(r){return this.log("warn",`\u26A0\uFE0F Signature validation error: ${r.message}`),!1}}mineBlock(t=10){let r=this.mempool.splice(0,t),i={height:this.currentBlock.height+1,timestamp:Date.now(),transactions:r,transactionCount:r.length,previousBlockHash:this.currentBlock.hash||"0000000000000000000000000000000000000000000000000000000000000000"},n=JSON.stringify({height:i.height,timestamp:i.timestamp,previousBlockHash:i.previousBlockHash,transactions:r.map(o=>o.id||o.toString())});return i.hash=this.bsv.crypto.Hash.sha256(h.Buffer.from(n)).toString("hex"),this.currentBlock=i,this.log("info",`\u26CF\uFE0F Mined block ${i.height} with ${r.length} transactions`),this.log("debug",`\u{1F4E6} Block hash: ${i.hash}`),i}getMempoolStats(){return{transactionCount:this.mempool.length,transactions:this.mempool.map(t=>({id:t.id||"unknown",size:t.toBuffer?t.toBuffer().length:0,inputs:t.inputs?t.inputs.length:0,outputs:t.outputs?t.outputs.length:0}))}}getBlockchainStats(){return{currentHeight:this.currentBlock.height,currentBlockHash:this.currentBlock.hash,currentBlockTimestamp:this.currentBlock.timestamp,mempoolSize:this.mempool.length,difficulty:this.options.difficulty,blockTime:this.options.blockTime}}reset(){this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[],this.log("info","\u{1F504} Miner reset to genesis state")}log(t,r){let i={error:0,warn:1,info:2,debug:3},n=i[this.options.logLevel]||2;if(i[t]<=n){let o=new Date().toISOString();console.log(`[${o}] [${t.toUpperCase()}] ${r}`)}}};OC.exports=t7});var PC=k((yve,AC)=>{v();var Ne=Te(),Bl=class{static createSignature(t,r,i,n,o,a=null){a=a||Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID;let s=Ne.Transaction.sighash.sign(t,r,a,i,n,new Ne.crypto.BN(o));return h.Buffer.concat([s.toDER(),h.Buffer.from([a])])}static createMultisigScript(t,r){let i=new Ne.Script().add(Ne.Opcode[`OP_${t}`]);for(let n of r)i=i.add(n.toBuffer());return i.add(Ne.Opcode[`OP_${r.length}`]).add(Ne.Opcode.OP_CHECKMULTISIG)}static createMultisigUnlocking(t){let r=new Ne.Script().add(Ne.Opcode.OP_0);for(let i of t)r=r.add(i);return r}static createTimelockScript(t,r){let i=h.Buffer.from(t.toString(16).padStart(8,"0"),"hex").reverse();return new Ne.Script().add(i).add(Ne.Opcode.OP_CHECKLOCKTIMEVERIFY).add(Ne.Opcode.OP_DROP).add(r.toBuffer())}static createConditionalScript(t,r=null){let i=new Ne.Script().add(Ne.Opcode.OP_IF).add(t.toBuffer());return r&&(i=i.add(Ne.Opcode.OP_ELSE).add(r.toBuffer())),i.add(Ne.Opcode.OP_ENDIF)}static createP2PKHScript(t){return new Ne.Script().add(Ne.Opcode.OP_DUP).add(Ne.Opcode.OP_HASH160).add(t.toAddress().hashBuffer).add(Ne.Opcode.OP_EQUALVERIFY).add(Ne.Opcode.OP_CHECKSIG)}static createP2PKHUnlocking(t,r){return new Ne.Script().add(t).add(r.toBuffer())}static getPreimage(t,r,i,n,o=null){return o=o||Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID,Ne.Transaction.sighash.sighash(t,o,r,i,new Ne.crypto.BN(n))}static createDataScript(t){return typeof t=="string"&&(t=h.Buffer.from(t,"utf8")),new Ne.Script().add(t)}static createOpReturnScript(t){return typeof t=="string"&&(t=h.Buffer.from(t,"utf8")),new Ne.Script().add(Ne.Opcode.OP_FALSE).add(Ne.Opcode.OP_RETURN).add(t)}static validateTransaction(t){try{return t.verify()}catch(r){return console.error("Transaction validation error:",r.message),!1}}static validateScript(t,r,i,n){try{return new Ne.Script.Interpreter().verify(t,r,i,n,Ne.Script.Interpreter.SCRIPT_VERIFY_P2SH|Ne.Script.Interpreter.SCRIPT_VERIFY_STRICTENC|Ne.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID|Ne.Script.Interpreter.SCRIPT_ENABLE_MAGNETIC_OPCODES|Ne.Script.Interpreter.SCRIPT_ENABLE_MONOLITH_OPCODES)}catch(o){return console.error("Script validation error:",o.message),!1}}static createLowFeeTransaction(t,r,i=10){let n=new Ne.Transaction().feePerKb(i);for(let o of t)n=n.from(o);for(let o of r)n=n.to(o.address,o.satoshis);return n}};Bl.SIGHASH_ALL=Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID;Bl.SIGHASH_NONE=Ne.crypto.Signature.SIGHASH_NONE|Ne.crypto.Signature.SIGHASH_FORKID;Bl.SIGHASH_SINGLE=Ne.crypto.Signature.SIGHASH_SINGLE|Ne.crypto.Signature.SIGHASH_FORKID;AC.exports=Bl});var Y6=k((_ve,CC)=>{"use strict";v();var O1=Te(),kC=h.Buffer.from("ord","utf8");function r7(){return O1.Script}function RC(){return O1.Opcode}function BC(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"an array";var t=typeof e;return(t==="object"?"an ":"a ")+t}function TC(e,t){if(h.Buffer.isBuffer(e))return e;if(typeof e=="string")return h.Buffer.from(e,"utf8");throw new Error(t+" must be a string or Buffer, got "+BC(e))}var eoe=["data","body","payload","text","message"];function toe(e){var t=r7(),r=e.lock!=null,i=e.address!=null;if(r&&i)throw new Error("buildInscription accepts `lock` or `address`, not both \u2014 they name different owners and one would be silently ignored");if(r){var n;if(e.lock instanceof t)n=e.lock;else if(h.Buffer.isBuffer(e.lock))n=t.fromBuffer(e.lock);else if(typeof e.lock=="string")n=t.fromHex(e.lock);else throw new Error("lock must be a Script, Buffer, or hex string, got "+BC(e.lock));if(!n.chunks.length&&!e.allowEmptyLock)throw new Error("lock is empty: the inscription would carry no locking script at all and the ordinal would be spendable by anyone. Pass a real lock, or { allowEmptyLock: true } if you are appending this envelope to your own script");return n}if(i){var o=e.address instanceof O1.Address?e.address:O1.Address.fromString(String(e.address));return t.buildPublicKeyHashOut(o)}throw new Error("buildInscription requires an address or a lock script")}function MC(e){e=e||{};var t=RC(),r=toe(e);if(e.content==null){var i=eoe.filter(function(s){return e[s]!=null})[0];throw new Error("buildInscription requires `content`"+(i?" \u2014 received `"+i+"`, which is not read":"")+". Omitting it would inscribe an empty payload; pass content: '' if that is intended")}var n=TC(e.content,"content"),o;if(e.contentType==null){if(h.Buffer.isBuffer(e.content))throw new Error("contentType is required when content is a Buffer (e.g. 'image/png', 'application/octet-stream') \u2014 it cannot be inferred from bytes");o=h.Buffer.from("text/plain","utf8")}else if(o=TC(e.contentType,"contentType"),!o.length)throw new Error("contentType must not be empty");var a=r7().fromBuffer(r.toBuffer());return a.add(t.OP_FALSE),a.add(t.OP_IF),a.add(kC),a.add(t.OP_1),a.add(o),a.add(t.OP_0),a.add(n),a.add(t.OP_ENDIF),a}function E1(e,t){return e&&e.opcodenum===t&&e.buf==null}function NC(e){for(var t=r7(),r=RC(),i=e instanceof t?e:h.Buffer.isBuffer(e)?t.fromBuffer(e):t.fromHex(e),n=i.chunks,o=-1,a=0;a+2<n.length;a++)if(E1(n[a],r.OP_FALSE)&&E1(n[a+1],r.OP_IF)&&n[a+2].buf&&n[a+2].buf.equals(kC)){o=a;break}if(o===-1)return null;for(var s=h.Buffer.alloc(0),u=h.Buffer.alloc(0),c=n.length,l=o+3;l<n.length;l++){var m=n[l];if(E1(m,r.OP_ENDIF)){c=l;break}E1(m,r.OP_1)&&n[l+1]&&n[l+1].buf?(s=n[l+1].buf,l++):E1(m,r.OP_0)&&n[l+1]&&n[l+1].buf&&(u=n[l+1].buf,l++)}for(var w=new t,E=0;E<o;E++)w.chunks.push(n[E]);for(var P=c+1;P<n.length;P++)w.chunks.push(n[P]);return{contentType:s.toString("utf8"),content:u,contentText:u.toString("utf8"),lock:w}}function roe(e){try{return NC(e)!==null}catch{return!1}}function ioe(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new Error("satoshis must be a positive integer (1 for a standard 1Sat ordinal)");return new O1.Transaction.Output({script:MC(e),satoshis:t})}CC.exports={buildInscription:MC,parseInscription:NC,isInscription:roe,createInscriptionOutput:ioe}});var zC=k((Sve,jC)=>{"use strict";v();var qr=Te(),Nl=Tl(),i7=Go(),qC=Y6(),Yo=qr.Script,Xt=qr.Opcode,UC=qr.encoding.BufferReader,J6=Nl.SIGHASH_ALL_ANYONECANPAY_FORKID;function DC(e,t){return t&&t.length?e.add(h.Buffer.from(t)):e.add(Xt.OP_0)}function $6(e){return e.toBufferWriter().toBuffer()}function Cl(e,t){if(typeof e!="number"||!isFinite(e)||e<0||Math.floor(e)!==e)throw new Error(t+" must be a non-negative integer number of satoshis (got "+e+")");return e}function e5(e){return e instanceof Yo?e:h.Buffer.isBuffer(e)?Yo.fromBuffer(e):Yo.fromHex(e)}function FC(e){return e instanceof qr.Address?e:e&&typeof e.toAddress=="function"?e.toAddress():qr.Address.fromString(String(e))}function noe(e){if(h.Buffer.isBuffer(e)){if(e.length!==20)throw new Error("seller pubkeyhash buffer must be 20 bytes (HASH160)");return e}return e instanceof qr.PublicKey?qr.crypto.Hash.sha256ripemd160(e.toBuffer()):FC(e).hashBuffer}function Dl(e,t){return Cl(t,"payment price"),new qr.Transaction.Output({script:Yo.buildPublicKeyHashOut(FC(e)),satoshis:t})}function X6(e){if(e instanceof qr.Transaction.Output)return e;if(h.Buffer.isBuffer(e))return qr.Transaction.Output.fromBufferReader(new UC(e));var t=e.payTo!=null?e.payTo:e.address,r=e.satoshis!=null?e.satoshis:e.price;if(t==null||r==null)throw new Error("payment spec needs {address|payTo, satoshis|price}");return Dl(t,r)}function ooe(e){if(e.payOutputs){if(!e.payOutputs.length)throw new Error("payOutputs must be a non-empty array");return e.payOutputs.map(X6)}if(e.payOutput!=null)return[X6(e.payOutput)];if(e.price!=null){var t=e.payTo!=null?e.payTo:e.seller,r=t instanceof qr.Transaction.Output?t:Dl(t,e.price),i=[r];return e.royalties&&e.royalties.forEach(function(n){i.push(X6(n))}),i}throw new Error("buildOrdLock requires a price, a payOutput, or payOutputs")}function aoe(e){return h.Buffer.concat(e.map($6))}function t5(e){if(e=e||{},e.seller==null)throw new Error("buildOrdLock requires a seller");var t=noe(e.seller),r=aoe(ooe(e)),i=new Yo;if(i.add(Xt.OP_IF),i.add(Xt.OP_DUP).add(Xt.OP_HASH160),i.add(h.Buffer.from(t)).add(Xt.OP_EQUALVERIFY).add(Xt.OP_CHECKSIG),i.add(Xt.OP_ELSE),i.add(Xt.OP_DUP),Nl.pushTxCore(i,{sighashType:J6}),i.add(Xt.OP_VERIFY),Nl.assertSighashType(i,J6),Nl.extractHashOutputs(i),i.add(Xt.OP_TOALTSTACK),i.add(h.Buffer.from(r)).add(Xt.OP_CAT),i.add(Xt.OP_SWAP).add(Xt.OP_CAT),i.add(Xt.OP_HASH256),i.add(Xt.OP_FROMALTSTACK).add(Xt.OP_EQUAL),i.add(Xt.OP_ENDIF),e.inscription){var n=qC.buildInscription({lock:new Yo,allowEmptyLock:!0,contentType:e.inscription.contentType,content:e.inscription.content});n.chunks.forEach(function(o){i.chunks.push(o)})}return i}function Ml(e,t){return e&&e.opcodenum===t&&e.buf==null}function LC(e){for(var t=new UC(e),r=[];!t.eof();)r.push(qr.Transaction.Output.fromBufferReader(t));return r}function r5(e,t){var r=t&&t.network;try{for(var i=e5(e),n=i.chunks,o=0,a=-1,s=-1,u=-1,c=0;c<n.length;c++)if(Ml(n[c],Xt.OP_IF))o===0&&(a=c),o++;else if(Ml(n[c],Xt.OP_ELSE)&&o===1)s=c;else if(Ml(n[c],Xt.OP_ENDIF)&&(o--,o===0)){u=c;break}if(a===-1||s===-1||u===-1)return null;for(var l=null,m=a+1;m<s;m++)if(n[m].buf&&n[m].buf.length===20){l=n[m].buf;break}if(!l)return null;for(var w=null,E=s+1;E<u;E++)Ml(n[E],Xt.OP_TOALTSTACK)&&n[E+1]&&n[E+1].buf&&Ml(n[E+2],Xt.OP_CAT)&&Ml(n[E+3],Xt.OP_SWAP)&&(w=n[E+1].buf);if(!w)return null;var P=LC(w).map(function(K){var N=null;try{K.script.isPublicKeyHashOut()&&(N=K.script.toAddress(r).toString())}catch{}return{satoshis:K.satoshis,script:K.script,address:N}}),M=P.reduce(function(K,N){return K+N.satoshis},0),D=null,L=qC.parseInscription(i);L&&(D={contentType:L.contentType,content:L.content,contentText:L.contentText});var U=t5({seller:l,payOutputs:LC(w),inscription:L?{contentType:L.contentType,content:L.content}:void 0});return U.toHex()!==i.toHex()?null:{seller:{pubKeyHash:l,address:qr.Address.fromPublicKeyHash(l,r).toString()},payOutputs:P,payBlob:w,totalPrice:M,inscription:D}}catch{return null}}function soe(e,t){return r5(e,t)!==null}function uoe(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;return new qr.Transaction.Output({script:t5(e),satoshis:t})}function HC(e){e=e||{};var t=e.spend,r=e.lockingScript;if(!t||!r)throw new Error("purchase requires { spend, lockingScript }");var i=e.inputIndex||0,n=e.payoutIndex!=null?e.payoutIndex:1,o=e.satoshis!=null?e.satoshis:1,a=t.outputs||[],s=e.parsed||r5(r),u=e.payoutCount!=null?e.payoutCount:s?s.payOutputs.length:1;if(n+u>a.length)throw new Error("purchase: spend has fewer outputs than the pinned block requires (need "+(n+u)+", have "+a.length+")");if(e.validate!==!1&&s){var c=h.Buffer.concat(a.slice(n,n+u).map($6));if(!c.equals(s.payBlob))throw new Error("purchase: outputs ["+n+".."+(n+u-1)+"] do not match the listing payment \u2014 the seller (or a royalty/fee payee) would not be paid")}var l=h.Buffer.concat(a.slice(0,n).map($6)),m=h.Buffer.concat(a.slice(n+u).map($6)),w=Object.assign({sighashType:J6},e.grind||{}),E=Nl.grind(t,i,r,o,w),P=new Yo;return DC(P,m),DC(P,l),P.add(h.Buffer.from(E.preimage)),P.add(Xt.OP_FALSE),t.inputs[i].setScript(P),P}function foe(e){e=e||{};var t=e.privateKey,r=e.spend,i=e.lockingScript;if(!t||!r||!i)throw new Error("cancel requires { privateKey, spend, lockingScript }");var n=e.inputIndex||0,o=e.satoshis!=null?e.satoshis:1,a=e.sighashType!=null?e.sighashType:i7.SIGHASH,s=i7.signInput(r,t,n,i,o,a),u=new Yo;return u.add(h.Buffer.from(s)),u.add(t.toPublicKey().toBuffer()),u.add(Xt.OP_TRUE),r.inputs[n].setScript(u),u}function Q6(e,t,r,i){e.addInput(new qr.Transaction.Input({prevTxId:t.txid||t.prevTxId,outputIndex:t.outputIndex!=null?t.outputIndex:t.vout,script:Yo.empty()}),e5(r),i)}function n7(e,t,r){Cl(r.satoshis,"input "+t+" satoshis");var i=e5(r.script),n=i7.signInput(e,r.privateKey,t,i,r.satoshis,Nl.SIGHASH_ALL_FORKID),o=new Yo;o.add(h.Buffer.from(n)),o.add(r.privateKey.toPublicKey().toBuffer()),e.inputs[t].setScript(o)}function coe(e){e=e||{};var t=e.ordinal;if(!t||!t.script||!t.privateKey)throw new Error("buildListingTx requires ordinal { script, privateKey, txid, outputIndex }");var r=Cl(t.satoshis!=null?t.satoshis:1,"ordinal satoshis"),i=t5(e),n=e.funding||[],o=e.fee!=null?e.fee:500,a=n.reduce(function(c,l){return c+Cl(l.satoshis,"funding satoshis")},0),s=a-o;if(s<0)throw new Error("buildListingTx: insufficient funding \u2014 need "+o+" sat fee, funded "+a);var u=new qr.Transaction;return Q6(u,t,t.script,r),n.forEach(function(c){Q6(u,c,c.script,c.satoshis)}),u.addOutput(new qr.Transaction.Output({script:i,satoshis:r})),s>0&&u.addOutput(Dl(e.changeAddress||t.privateKey.toAddress(),s)),n7(u,0,{script:t.script,privateKey:t.privateKey,satoshis:r}),n.forEach(function(c,l){n7(u,1+l,c)}),{tx:u,listingScript:i,listingOutpoint:{txid:u.hash,outputIndex:0}}}function loe(e){e=e||{};var t=e.listing;if(!t||!t.script)throw new Error("buildPurchaseTx requires listing.script");if(!e.ordinalDestination)throw new Error("buildPurchaseTx requires ordinalDestination");if(!e.funding||!e.funding.length)throw new Error("buildPurchaseTx requires funding coins");var r=e5(t.script),i=r5(r);if(!i)throw new Error("buildPurchaseTx: listing.script is not a parseable OrdLock");var n=Cl(t.satoshis!=null?t.satoshis:1,"listing satoshis"),o=e.payOutputs?e.payOutputs.map(X6):i.payOutputs.map(function(m){return new qr.Transaction.Output({script:m.script,satoshis:m.satoshis})}),a=o.reduce(function(m,w){return m+w.satoshis},0),s=e.fee!=null?e.fee:500,u=e.funding.reduce(function(m,w){return m+Cl(w.satoshis,"funding satoshis")},0),c=u-a-s;if(c<0)throw new Error("buildPurchaseTx: insufficient funding \u2014 need "+(a+s)+" sat (payments "+a+" + fee "+s+"), funded "+u);var l=new qr.Transaction;return Q6(l,t,r,n),e.funding.forEach(function(m){Q6(l,m,m.script,m.satoshis)}),l.addOutput(Dl(e.ordinalDestination,n)),o.forEach(function(m){l.addOutput(m)}),c>0&&l.addOutput(Dl(e.changeAddress||e.ordinalDestination,c)),HC({spend:l,lockingScript:r,parsed:i,satoshis:n,inputIndex:0,payoutIndex:1,payoutCount:o.length,grind:e.grind}),e.funding.forEach(function(m,w){n7(l,1+w,m)}),l}jC.exports={ORDLOCK_SIGHASH:J6,buildOrdLock:t5,parseOrdLock:r5,isOrdLock:soe,listInscriptionOutput:uoe,payOutputFor:Dl,purchase:HC,cancel:foe,buildListingTx:coe,buildPurchaseTx:loe}});var uD=k((Eve,sD)=>{"use strict";v();var KC=Y6(),VC="application/bsv-20",o7=18,i5="18446744073709551615";function GC(e){return typeof e=="string"&&/^\d+$/.test(e)}function ZC(e){return e.length>i5.length||e.length===i5.length&&e>i5}function WC(e,t){var r;if(typeof e=="number"){if(!Number.isInteger(e)||e<0)throw new Error(t+" must be a non-negative integer");if(e>Number.MAX_SAFE_INTEGER)throw new Error(t+" exceeds Number.MAX_SAFE_INTEGER and would lose precision \u2014 pass it as a string");r=String(e)}else if(GC(e))r=e.replace(/^0+(?=\d)/,"");else throw new Error(t+" must be a non-negative integer (string or number)");if(ZC(r))throw new Error(t+" exceeds the uint64 maximum ("+i5+")");return r}function I1(e,t){var r=WC(e,t);if(!/[1-9]/.test(r))throw new Error(t+" must be greater than zero");return r}function YC(e){if(typeof e!="string"||!e.length)throw new Error("tick is required");if(h.Buffer.byteLength(e,"utf8")>4)throw new Error("tick must be 1\u20134 UTF-8 bytes");return e}function a7(e){var t=typeof e=="string"?Number(e):e;if(!Number.isInteger(t)||t<0||t>o7)throw new Error("dec must be an integer 0\u2026"+o7);return String(t)}var s7=/^[0-9a-fA-F]{64}_\d+$/;function u7(e){if(typeof e!="string"||!s7.test(e))throw new Error('id must be "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function f7(e,t){if(typeof e!="string"){var r=e===null?"null":Array.isArray(e)?"an array":(typeof e=="object"?"an ":"a ")+typeof e;throw new Error(t+" must be a string, got "+r)}if(!e.length)throw new Error(t+" must not be empty");return e}function $C(e){if(f7(e,"icon"),!s7.test(e))throw new Error('icon must be an outpoint reference "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function If(e,t){return t=t||{},KC.buildInscription({lock:t.lock,address:t.address,contentType:t.contentType||VC,content:JSON.stringify(e)})}function XC(e){e=e||{};var t={p:"bsv-20",op:"deploy",tick:YC(e.tick),max:I1(e.max,"max")};return e.lim!=null&&(t.lim=WC(e.lim,"lim")),e.dec!=null&&(t.dec=a7(e.dec)),If(t,e)}function JC(e,t,r){var i=t.tick!=null,n=t.id!=null;if(i&&n)throw new Error(r+" names a token by `tick` (v1) or `id` (BSV-21), not both");if(!i&&!n)throw new Error(r+" requires `tick` (v1) or `id` (BSV-21)");return n?e.id=u7(t.id):e.tick=YC(t.tick),e}function QC(e,t){if(e.amt!=null)throw new Error(t+" must not carry an amt \u2014 the specification forbids it, and a payload that does is discarded")}function eD(e){e=e||{};var t={p:"bsv-20",op:"mint"};return JC(t,e,"mint"),t.amt=I1(e.amt,"amt"),If(t,e)}function tD(e){e=e||{};var t={p:"bsv-20",op:"transfer",amt:I1(e.amt,"amt")};return JC(t,e,"transfer"),If(t,e)}function rD(e){if(e=e||{},e.tick!=null)throw new Error("burn is a BSV-21 operation and names its token by `id` (<txid>_<vout>), not `tick`");var t={p:"bsv-20",op:"burn",id:u7(e.id),amt:I1(e.amt,"amt")};return If(t,e)}function iD(e){e=e||{},QC(e,"deploy+auth");var t={p:"bsv-20",op:"deploy+auth"};return e.dec!=null&&(t.dec=a7(e.dec)),e.sym!=null&&(t.sym=f7(e.sym,"sym")),e.icon!=null&&(t.icon=$C(e.icon)),If(t,e)}function nD(e){e=e||{},QC(e,"auth");var t={p:"bsv-20",op:"auth",id:u7(e.id)};return If(t,e)}function oD(e){e=e||{};var t={p:"bsv-20",op:"deploy+mint",amt:I1(e.amt,"amt")};return e.dec!=null&&(t.dec=a7(e.dec)),e.sym!=null&&(t.sym=f7(e.sym,"sym")),e.icon!=null&&(t.icon=$C(e.icon)),If(t,e)}function Af(e,t){var r=Te();return new r.Transaction.Output({script:e,satoshis:t??1})}function hoe(e){return Af(XC(e),e&&e.satoshis)}function doe(e){return Af(eD(e),e&&e.satoshis)}function poe(e){return Af(tD(e),e&&e.satoshis)}function goe(e){return Af(oD(e),e&&e.satoshis)}function voe(e){return Af(rD(e),e&&e.satoshis)}function moe(e){return Af(iD(e),e&&e.satoshis)}function yoe(e){return Af(nD(e),e&&e.satoshis)}function boe(e){var t=Te();if(e&&typeof e=="object"&&!h.Buffer.isBuffer(e)&&!(e instanceof t.Script)||typeof e=="string"&&e.trim()[0]==="{")return e;var r=KC.parseInscription(e);return r?r.contentText:null}var _oe={deploy:{need:["tick","max"]},mint:{need:["amt"],tickOrId:!0},transfer:{need:["amt"],tickOrId:!0},"deploy+mint":{need:["amt"]},"deploy+auth":{need:[],noAmt:!0},auth:{need:["id"],noAmt:!0},burn:{need:["id","amt"]}};function woe(e){var t=typeof e=="number"?Number.isInteger(e)&&e>=0?String(e):null:GC(e)?e:null;return t==null?!1:!ZC(t.replace(/^0+(?=\d)/,""))}function Soe(e){if(!e||e.p!=="bsv-20"||typeof e.op!="string")return!1;var t=_oe[e.op];if(!t)return!1;for(var r=0;r<t.need.length;r++)if(e[t.need[r]]==null)return!1;if(t.tickOrId&&e.tick==null==(e.id==null)||t.noAmt&&e.amt!=null||e.tick!=null&&(typeof e.tick!="string"||!e.tick.length||h.Buffer.byteLength(e.tick,"utf8")>4)||e.id!=null&&(typeof e.id!="string"||!s7.test(e.id)))return!1;for(var i=["amt","max","lim"],n=0;n<i.length;n++)if(e[i[n]]!=null&&!woe(e[i[n]]))return!1;if(e.dec!=null){var o=typeof e.dec=="string"?Number(e.dec):e.dec;if(!Number.isInteger(o)||o<0||o>o7)return!1}return!0}function aD(e){try{var t=boe(e);if(t==null)return null;var r=typeof t=="object"?t:JSON.parse(t);return Soe(r)?r:null}catch{return null}}function xoe(e){return aD(e)!==null}sD.exports={CONTENT_TYPE:VC,buildDeploy:XC,buildMint:eD,buildTransfer:tD,buildDeployMint:oD,buildBurn:rD,buildDeployAuth:iD,buildAuth:nD,createDeployOutput:hoe,createMintOutput:doe,createTransferOutput:poe,createDeployMintOutput:goe,createBurnOutput:voe,createDeployAuthOutput:moe,createAuthOutput:yoe,parseBsv20:aD,isBsv20:xoe}});var cD=k((Ive,fD)=>{"use strict";v();var A1=Y6(),$o=zC(),Eoe=uD();function Ooe(e){if(!Array.isArray(e)||!e.length)throw new Error("batchInscriptionOutputs requires a non-empty array of items");return e.map(function(t){return A1.createInscriptionOutput(t)})}fD.exports={buildInscription:A1.buildInscription,parseInscription:A1.parseInscription,isInscription:A1.isInscription,createInscriptionOutput:A1.createInscriptionOutput,batchInscriptionOutputs:Ooe,ORDLOCK_SIGHASH:$o.ORDLOCK_SIGHASH,buildOrdLock:$o.buildOrdLock,parseOrdLock:$o.parseOrdLock,isOrdLock:$o.isOrdLock,listInscriptionOutput:$o.listInscriptionOutput,payOutputFor:$o.payOutputFor,purchaseOrdLock:$o.purchase,cancelOrdLock:$o.cancel,buildListingTx:$o.buildListingTx,buildPurchaseTx:$o.buildPurchaseTx,BSV20:Eoe}});var hD=k((Pve,lD)=>{"use strict";v();var n5=_r();async function Ioe(e){e=e||{};var t=e.alg||"ES256",r=e.kid||"key-"+Date.now();if(t!=="ES256"&&t!=="ES256K")throw new Error("Invalid algorithm. Must be ES256 or ES256K");var i;t==="ES256"?i=n5.generateKeyPairSync("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}):i=n5.generateKeyPairSync("ec",{namedCurve:"secp256k1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});var n=n5.createPublicKey(i.publicKey).export({format:"jwk"}),o=n5.createPrivateKey(i.privateKey).export({format:"jwk"});return n.kid=r,n.alg=t,n.use="sig",n.kty="EC",o.kid=r,o.alg=t,o.use="sig",o.kty="EC",{privateJwk:o,publicJwk:n,kid:r,alg:t}}function Aoe(e){if(!e.domain)throw new Error("domain is required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=[],n=[];if(e.p256){var o={id:r+"#"+e.p256.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.p256.jwk};i.push(o),n.push(e.p256.jwk)}if(e.k1){var a={id:r+"#"+e.k1.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.k1.jwk};i.push(a),n.push(e.k1.jwk)}if(i.length===0)throw new Error("At least one key (p256 or k1) must be provided");var s={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:i,authentication:i.map(function(c){return c.id}),assertionMethod:i.map(function(c){return c.id})};e.controllerName&&(s.controller=e.controllerName);var u={keys:n};return{did:r,didDocument:s,jwks:u}}function Poe(e){if(!e.domain||!e.newKey)throw new Error("domain and newKey are required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=e.keepOldForDays||30,n={id:r+"#"+e.newKey.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.newKey.jwk},o={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:[n],authentication:[n.id],assertionMethod:[n.id],rotationInfo:{rotatedAt:new Date().toISOString(),gracePeriodDays:i}},a={keys:[e.newKey.jwk]};return{didDocument:o,jwks:a}}lD.exports={generateIssuerKeys:Ioe,buildDidWebDocuments:Aoe,rotateIssuerKey:Poe}});var c7=k((kve,dD)=>{"use strict";v();var P1=_r(),T1={ES256:"P-256",ES256K:"secp256k1"},Toe=["ES256","ES256K"];function o5(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function a5(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return h.Buffer.from(e,"base64")}async function koe(e){if(!e.issuerDid||!e.subjectId||!e.credentialSubject||!e.privateJwk)throw new Error("issuerDid, subjectId, credentialSubject, and privateJwk are required");var t=e.alg||"ES256";if(!T1[t])throw new Error("Unsupported algorithm: "+t);if(e.privateJwk.crv&&e.privateJwk.crv!==T1[t])throw new Error("Key curve "+e.privateJwk.crv+" does not match alg "+t);var r=e.kid||e.privateJwk.kid,i=e.types||["VerifiableCredential"],n=e.expSeconds||365*24*60*60,o=Math.floor(Date.now()/1e3),a=new Date().toISOString(),s={"@context":["https://www.w3.org/2018/credentials/v1"],type:i,issuer:e.issuerDid,issuanceDate:a,credentialSubject:Object.assign({id:e.subjectId},e.credentialSubject)},u={iss:e.issuerDid,sub:e.subjectId,iat:o,exp:o+n,vc:s},c={alg:t,typ:"JWT",kid:r},l=o5(h.Buffer.from(JSON.stringify(c))),m=o5(h.Buffer.from(JSON.stringify(u))),w=l+"."+m,E=P1.createPrivateKey({key:e.privateJwk,format:"jwk"}),P=P1.sign("sha256",h.Buffer.from(w),{key:E,dsaEncoding:"ieee-p1363"}),M=o5(P),D=w+"."+M;return{jwt:D}}async function Roe(e,t){t=t||{};try{if(typeof e!="string")return{valid:!1,error:"Invalid JWT format"};var r=e.split(".");if(r.length!==3)return{valid:!1,error:"Invalid JWT format"};var i=r[0],n=r[1],o=r[2],a=JSON.parse(a5(i).toString()),s=JSON.parse(a5(n).toString()),u=a5(o),c=t.allowedAlgs||Toe;if(!a.alg||c.indexOf(a.alg)===-1||!T1[a.alg])return{valid:!1,error:"Algorithm not allowed: "+a.alg,header:a,payload:s};var l=Math.floor(Date.now()/1e3),m=t.clockToleranceSec||60;if(t.requireExpiration&&!s.exp)return{valid:!1,error:"JWT missing required exp claim",header:a,payload:s};if(s.exp&&s.exp<l-m)return{valid:!1,error:"JWT expired",header:a,payload:s};if(s.nbf&&s.nbf>l+m)return{valid:!1,error:"JWT not yet valid",header:a,payload:s};if(t.expectedIssuerDid&&s.iss!==t.expectedIssuerDid)return{valid:!1,error:"Unexpected issuer",header:a,payload:s};var w;if(t.didResolver){var E=await t.didResolver(s.iss);if(!E||!E.jwks||!E.jwks.keys)return{valid:!1,error:"Failed to resolve issuer DID",header:a,payload:s};var P=E.jwks.keys.find(function(U){return U.kid===a.kid});if(!P)return{valid:!1,error:"Key not found in JWKS",header:a,payload:s};w=P}else return{valid:!1,error:"DID resolver required for verification",header:a,payload:s};if(w.crv&&w.crv!==T1[a.alg])return{valid:!1,error:"Key curve does not match algorithm",header:a,payload:s};var M=i+"."+n,D=P1.createPublicKey({key:w,format:"jwk"}),L=P1.verify("sha256",h.Buffer.from(M),{key:D,dsaEncoding:"ieee-p1363"},u);if(!L&&t.allowLegacyDER)try{L=P1.verify("sha256",h.Buffer.from(M),{key:D,dsaEncoding:"der"},u)}catch{L=!1}return L?{valid:!0,header:a,payload:s}:{valid:!1,error:"Invalid signature",header:a,payload:s}}catch(U){return{valid:!1,error:U.message||"Verification failed"}}}dD.exports={issueVcJwt:koe,verifyVcJwt:Roe,base64UrlEncode:o5,base64UrlDecode:a5,ALG_TO_CRV:T1}});var gD=k((Bve,pD)=>{"use strict";v();function Boe(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}pD.exports=Boe});var k1=k(Ei=>{"use strict";v();var Moe=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function Noe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Ei.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var i in r)Noe(r,i)&&(e[i]=r[i])}}return e};Ei.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var Coe={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+i),n);return}for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){var t,r,i,n,o,a;for(i=0,t=0,r=e.length;t<r;t++)i+=e[t].length;for(a=new Uint8Array(i),n=0,t=0,r=e.length;t<r;t++)o=e[t],a.set(o,n),n+=o.length;return a}},Doe={arraySet:function(e,t,r,i,n){for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){return[].concat.apply([],e)}};Ei.setTyped=function(e){e?(Ei.Buf8=Uint8Array,Ei.Buf16=Uint16Array,Ei.Buf32=Int32Array,Ei.assign(Ei,Coe)):(Ei.Buf8=Array,Ei.Buf16=Array,Ei.Buf32=Array,Ei.assign(Ei,Doe))};Ei.setTyped(Moe)});var qD=k(Ul=>{"use strict";v();var Loe=k1(),qoe=4,vD=0,mD=1,Uoe=2;function ql(e){for(var t=e.length;--t>=0;)e[t]=0}var Foe=0,xD=1,Hoe=2,joe=3,zoe=258,m7=29,D1=256,B1=D1+1+m7,Ll=30,y7=19,ED=2*B1+1,Pf=15,l7=16,Koe=7,b7=256,OD=16,ID=17,AD=18,g7=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],s5=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Voe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],PD=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Goe=512,Ja=new Array((B1+2)*2);ql(Ja);var R1=new Array(Ll*2);ql(R1);var M1=new Array(Goe);ql(M1);var N1=new Array(zoe-joe+1);ql(N1);var _7=new Array(m7);ql(_7);var u5=new Array(Ll);ql(u5);function h7(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}var TD,kD,RD;function d7(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function BD(e){return e<256?M1[e]:M1[256+(e>>>7)]}function C1(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Ci(e,t,r){e.bi_valid>l7-r?(e.bi_buf|=t<<e.bi_valid&65535,C1(e,e.bi_buf),e.bi_buf=t>>l7-e.bi_valid,e.bi_valid+=r-l7):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function Xo(e,t,r){Ci(e,r[t*2],r[t*2+1])}function MD(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function Zoe(e){e.bi_valid===16?(C1(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Woe(e,t){var r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,l,m,w,E,P,M=0;for(w=0;w<=Pf;w++)e.bl_count[w]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<ED;c++)l=e.heap[c],w=r[r[l*2+1]*2+1]+1,w>u&&(w=u,M++),r[l*2+1]=w,!(l>i)&&(e.bl_count[w]++,E=0,l>=s&&(E=a[l-s]),P=r[l*2],e.opt_len+=P*(w+E),o&&(e.static_len+=P*(n[l*2+1]+E)));if(M!==0){do{for(w=u-1;e.bl_count[w]===0;)w--;e.bl_count[w]--,e.bl_count[w+1]+=2,e.bl_count[u]--,M-=2}while(M>0);for(w=u;w!==0;w--)for(l=e.bl_count[w];l!==0;)m=e.heap[--c],!(m>i)&&(r[m*2+1]!==w&&(e.opt_len+=(w-r[m*2+1])*r[m*2],r[m*2+1]=w),l--)}}function ND(e,t,r){var i=new Array(Pf+1),n=0,o,a;for(o=1;o<=Pf;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=t;a++){var s=e[a*2+1];s!==0&&(e[a*2]=MD(i[s]++,s))}}function Yoe(){var e,t,r,i,n,o=new Array(Pf+1);for(r=0,i=0;i<m7-1;i++)for(_7[i]=r,e=0;e<1<<g7[i];e++)N1[r++]=i;for(N1[r-1]=i,n=0,i=0;i<16;i++)for(u5[i]=n,e=0;e<1<<s5[i];e++)M1[n++]=i;for(n>>=7;i<Ll;i++)for(u5[i]=n<<7,e=0;e<1<<s5[i]-7;e++)M1[256+n++]=i;for(t=0;t<=Pf;t++)o[t]=0;for(e=0;e<=143;)Ja[e*2+1]=8,e++,o[8]++;for(;e<=255;)Ja[e*2+1]=9,e++,o[9]++;for(;e<=279;)Ja[e*2+1]=7,e++,o[7]++;for(;e<=287;)Ja[e*2+1]=8,e++,o[8]++;for(ND(Ja,B1+1,o),e=0;e<Ll;e++)R1[e*2+1]=5,R1[e*2]=MD(e,5);TD=new h7(Ja,g7,D1+1,B1,Pf),kD=new h7(R1,s5,0,Ll,Pf),RD=new h7(new Array(0),Voe,0,y7,Koe)}function CD(e){var t;for(t=0;t<B1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Ll;t++)e.dyn_dtree[t*2]=0;for(t=0;t<y7;t++)e.bl_tree[t*2]=0;e.dyn_ltree[b7*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function DD(e){e.bi_valid>8?C1(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function $oe(e,t,r,i){DD(e),i&&(C1(e,r),C1(e,~r)),Loe.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function yD(e,t,r,i){var n=t*2,o=r*2;return e[n]<e[o]||e[n]===e[o]&&i[t]<=i[r]}function p7(e,t,r){for(var i=e.heap[r],n=r<<1;n<=e.heap_len&&(n<e.heap_len&&yD(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!yD(t,i,e.heap[n],e.depth));)e.heap[r]=e.heap[n],r=n,n<<=1;e.heap[r]=i}function bD(e,t,r){var i,n,o=0,a,s;if(e.last_lit!==0)do i=e.pending_buf[e.d_buf+o*2]<<8|e.pending_buf[e.d_buf+o*2+1],n=e.pending_buf[e.l_buf+o],o++,i===0?Xo(e,n,t):(a=N1[n],Xo(e,a+D1+1,t),s=g7[a],s!==0&&(n-=_7[a],Ci(e,n,s)),i--,a=BD(i),Xo(e,a,r),s=s5[a],s!==0&&(i-=u5[a],Ci(e,i,s)));while(o<e.last_lit);Xo(e,b7,t)}function v7(e,t){var r=t.dyn_tree,i=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.elems,a,s,u=-1,c;for(e.heap_len=0,e.heap_max=ED,a=0;a<o;a++)r[a*2]!==0?(e.heap[++e.heap_len]=u=a,e.depth[a]=0):r[a*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,n&&(e.static_len-=i[c*2+1]);for(t.max_code=u,a=e.heap_len>>1;a>=1;a--)p7(e,r,a);c=o;do a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],p7(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=s,r[c*2]=r[a*2]+r[s*2],e.depth[c]=(e.depth[a]>=e.depth[s]?e.depth[a]:e.depth[s])+1,r[a*2+1]=r[s*2+1]=c,e.heap[1]=c++,p7(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Woe(e,t),ND(r,u,e.bl_count)}function _D(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),t[(r+1)*2+1]=65535,i=0;i<=r;i++)o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)&&(s<c?e.bl_tree[o*2]+=s:o!==0?(o!==n&&e.bl_tree[o*2]++,e.bl_tree[OD*2]++):s<=10?e.bl_tree[ID*2]++:e.bl_tree[AD*2]++,s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4))}function wD(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),i=0;i<=r;i++)if(o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)){if(s<c)do Xo(e,o,e.bl_tree);while(--s!==0);else o!==0?(o!==n&&(Xo(e,o,e.bl_tree),s--),Xo(e,OD,e.bl_tree),Ci(e,s-3,2)):s<=10?(Xo(e,ID,e.bl_tree),Ci(e,s-3,3)):(Xo(e,AD,e.bl_tree),Ci(e,s-11,7));s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4)}}function Xoe(e){var t;for(_D(e,e.dyn_ltree,e.l_desc.max_code),_D(e,e.dyn_dtree,e.d_desc.max_code),v7(e,e.bl_desc),t=y7-1;t>=3&&e.bl_tree[PD[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Joe(e,t,r,i){var n;for(Ci(e,t-257,5),Ci(e,r-1,5),Ci(e,i-4,4),n=0;n<i;n++)Ci(e,e.bl_tree[PD[n]*2+1],3);wD(e,e.dyn_ltree,t-1),wD(e,e.dyn_dtree,r-1)}function Qoe(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return vD;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return mD;for(r=32;r<D1;r++)if(e.dyn_ltree[r*2]!==0)return mD;return vD}var SD=!1;function eae(e){SD||(Yoe(),SD=!0),e.l_desc=new d7(e.dyn_ltree,TD),e.d_desc=new d7(e.dyn_dtree,kD),e.bl_desc=new d7(e.bl_tree,RD),e.bi_buf=0,e.bi_valid=0,CD(e)}function LD(e,t,r,i){Ci(e,(Foe<<1)+(i?1:0),3),$oe(e,t,r,!0)}function tae(e){Ci(e,xD<<1,3),Xo(e,b7,Ja),Zoe(e)}function rae(e,t,r,i){var n,o,a=0;e.level>0?(e.strm.data_type===Uoe&&(e.strm.data_type=Qoe(e)),v7(e,e.l_desc),v7(e,e.d_desc),a=Xoe(e),n=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=n&&(n=o)):n=o=r+5,r+4<=n&&t!==-1?LD(e,t,r,i):e.strategy===qoe||o===n?(Ci(e,(xD<<1)+(i?1:0),3),bD(e,Ja,R1)):(Ci(e,(Hoe<<1)+(i?1:0),3),Joe(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),bD(e,e.dyn_ltree,e.dyn_dtree)),CD(e),i&&DD(e)}function iae(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(N1[r]+D1+1)*2]++,e.dyn_dtree[BD(t)*2]++),e.last_lit===e.lit_bufsize-1}Ul._tr_init=eae;Ul._tr_stored_block=LD;Ul._tr_flush_block=rae;Ul._tr_tally=iae;Ul._tr_align=tae});var w7=k((qve,UD)=>{"use strict";v();function nae(e,t,r,i){for(var n=e&65535|0,o=e>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do n=n+t[i++]|0,o=o+n|0;while(--a);n%=65521,o%=65521}return n|o<<16|0}UD.exports=nae});var S7=k((Fve,FD)=>{"use strict";v();function oae(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var aae=oae();function sae(e,t,r,i){var n=aae,o=i+r;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[(e^t[a])&255];return e^-1}FD.exports=sae});var jD=k((jve,HD)=>{"use strict";v();HD.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var XD=k(ea=>{"use strict";v();var Oi=k1(),En=qD(),GD=w7(),qs=S7(),uae=jD(),Bf=0,fae=1,cae=3,zs=4,zD=5,Qo=0,KD=1,On=-2,lae=-3,x7=-5,hae=-1,dae=1,f5=2,pae=3,gae=4,vae=0,mae=2,d5=8,yae=9,bae=15,_ae=8,wae=29,Sae=256,O7=Sae+1+wae,xae=30,Eae=19,Oae=2*O7+1,Iae=15,bt=3,Hs=258,so=Hs+bt+1,Aae=32,p5=42,I7=69,c5=73,l5=91,h5=103,Tf=113,q1=666,Ur=1,U1=2,kf=3,jl=4,Pae=3;function js(e,t){return e.msg=uae[t],t}function VD(e){return(e<<1)-(e>4?9:0)}function Fs(e){for(var t=e.length;--t>=0;)e[t]=0}function Us(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Oi.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function oi(e,t){En._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Us(e.strm)}function Pt(e,t){e.pending_buf[e.pending++]=t}function L1(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function Tae(e,t,r,i){var n=e.avail_in;return n>i&&(n=i),n===0?0:(e.avail_in-=n,Oi.arraySet(t,e.input,e.next_in,n,r),e.state.wrap===1?e.adler=GD(e.adler,t,n,r):e.state.wrap===2&&(e.adler=qs(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function ZD(e,t){var r=e.max_chain_length,i=e.strstart,n,o,a=e.prev_length,s=e.nice_match,u=e.strstart>e.w_size-so?e.strstart-(e.w_size-so):0,c=e.window,l=e.w_mask,m=e.prev,w=e.strstart+Hs,E=c[i+a-1],P=c[i+a];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(n=t,!(c[n+a]!==P||c[n+a-1]!==E||c[n]!==c[i]||c[++n]!==c[i+1])){i+=2,n++;do;while(c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&i<w);if(o=Hs-(w-i),i=w-Hs,o>a){if(e.match_start=t,a=o,o>=s)break;E=c[i+a-1],P=c[i+a]}}while((t=m[t&l])>u&&--r!==0);return a<=e.lookahead?a:e.lookahead}function Rf(e){var t=e.w_size,r,i,n,o,a;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-so)){Oi.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do n=e.head[--r],e.head[r]=n>=t?n-t:0;while(--i);i=t,r=i;do n=e.prev[--r],e.prev[r]=n>=t?n-t:0;while(--i);o+=t}if(e.strm.avail_in===0)break;if(i=Tae(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=bt)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+bt-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<bt)););}while(e.lookahead<so&&e.strm.avail_in!==0)}function kae(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Rf(e),e.lookahead===0&&t===Bf)return Ur;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((e.strstart===0||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,oi(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-so&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):(e.strstart>e.block_start&&(oi(e,!1),e.strm.avail_out===0),Ur)}function E7(e,t){for(var r,i;;){if(e.lookahead<so){if(Rf(e),e.lookahead<so&&t===Bf)return Ur;if(e.lookahead===0)break}if(r=0,e.lookahead>=bt&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-so&&(e.match_length=ZD(e,r)),e.match_length>=bt)if(i=En._tr_tally(e,e.strstart-e.match_start,e.match_length-bt),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=bt){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=e.strstart<bt-1?e.strstart:bt-1,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Fl(e,t){for(var r,i,n;;){if(e.lookahead<so){if(Rf(e),e.lookahead<so&&t===Bf)return Ur;if(e.lookahead===0)break}if(r=0,e.lookahead>=bt&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=bt-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-so&&(e.match_length=ZD(e,r),e.match_length<=5&&(e.strategy===dae||e.match_length===bt&&e.strstart-e.match_start>4096)&&(e.match_length=bt-1)),e.prev_length>=bt&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-bt,i=En._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-bt),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=n&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=bt-1,e.strstart++,i&&(oi(e,!1),e.strm.avail_out===0))return Ur}else if(e.match_available){if(i=En._tr_tally(e,0,e.window[e.strstart-1]),i&&oi(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return Ur}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=En._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<bt-1?e.strstart:bt-1,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Rae(e,t){for(var r,i,n,o,a=e.window;;){if(e.lookahead<=Hs){if(Rf(e),e.lookahead<=Hs&&t===Bf)return Ur;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=bt&&e.strstart>0&&(n=e.strstart-1,i=a[n],i===a[++n]&&i===a[++n]&&i===a[++n])){o=e.strstart+Hs;do;while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);e.match_length=Hs-(o-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=bt?(r=En._tr_tally(e,1,e.match_length-bt),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Bae(e,t){for(var r;;){if(e.lookahead===0&&(Rf(e),e.lookahead===0)){if(t===Bf)return Ur;break}if(e.match_length=0,r=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Jo(e,t,r,i,n){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=i,this.func=n}var Hl;Hl=[new Jo(0,0,0,0,kae),new Jo(4,4,8,4,E7),new Jo(4,5,16,8,E7),new Jo(4,6,32,32,E7),new Jo(4,4,16,16,Fl),new Jo(8,16,32,32,Fl),new Jo(8,16,128,128,Fl),new Jo(8,32,128,256,Fl),new Jo(32,128,258,1024,Fl),new Jo(32,258,258,4096,Fl)];function Mae(e){e.window_size=2*e.w_size,Fs(e.head),e.max_lazy_match=Hl[e.level].max_lazy,e.good_match=Hl[e.level].good_length,e.nice_match=Hl[e.level].nice_length,e.max_chain_length=Hl[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=bt-1,e.match_available=0,e.ins_h=0}function Nae(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=d5,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Oi.Buf16(Oae*2),this.dyn_dtree=new Oi.Buf16((2*xae+1)*2),this.bl_tree=new Oi.Buf16((2*Eae+1)*2),Fs(this.dyn_ltree),Fs(this.dyn_dtree),Fs(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Oi.Buf16(Iae+1),this.heap=new Oi.Buf16(2*O7+1),Fs(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Oi.Buf16(2*O7+1),Fs(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function WD(e){var t;return!e||!e.state?js(e,On):(e.total_in=e.total_out=0,e.data_type=mae,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?p5:Tf,e.adler=t.wrap===2?0:1,t.last_flush=Bf,En._tr_init(t),Qo)}function YD(e){var t=WD(e);return t===Qo&&Mae(e.state),t}function Cae(e,t){return!e||!e.state||e.state.wrap!==2?On:(e.state.gzhead=t,Qo)}function $D(e,t,r,i,n,o){if(!e)return On;var a=1;if(t===hae&&(t=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>yae||r!==d5||i<8||i>15||t<0||t>9||o<0||o>gae)return js(e,On);i===8&&(i=9);var s=new Nae;return e.state=s,s.strm=e,s.wrap=a,s.gzhead=null,s.w_bits=i,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=n+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+bt-1)/bt),s.window=new Oi.Buf8(s.w_size*2),s.head=new Oi.Buf16(s.hash_size),s.prev=new Oi.Buf16(s.w_size),s.lit_bufsize=1<<n+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Oi.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=o,s.method=r,YD(e)}function Dae(e,t){return $D(e,t,d5,bae,_ae,vae)}function Lae(e,t){var r,i,n,o;if(!e||!e.state||t>zD||t<0)return e?js(e,On):On;if(i=e.state,!e.output||!e.input&&e.avail_in!==0||i.status===q1&&t!==zs)return js(e,e.avail_out===0?x7:On);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===p5)if(i.wrap===2)e.adler=0,Pt(i,31),Pt(i,139),Pt(i,8),i.gzhead?(Pt(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Pt(i,i.gzhead.time&255),Pt(i,i.gzhead.time>>8&255),Pt(i,i.gzhead.time>>16&255),Pt(i,i.gzhead.time>>24&255),Pt(i,i.level===9?2:i.strategy>=f5||i.level<2?4:0),Pt(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(Pt(i,i.gzhead.extra.length&255),Pt(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=qs(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=I7):(Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,i.level===9?2:i.strategy>=f5||i.level<2?4:0),Pt(i,Pae),i.status=Tf);else{var a=d5+(i.w_bits-8<<4)<<8,s=-1;i.strategy>=f5||i.level<2?s=0:i.level<6?s=1:i.level===6?s=2:s=3,a|=s<<6,i.strstart!==0&&(a|=Aae),a+=31-a%31,i.status=Tf,L1(i,a),i.strstart!==0&&(L1(i,e.adler>>>16),L1(i,e.adler&65535)),e.adler=1}if(i.status===I7)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size));)Pt(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=c5)}else i.status=c5;if(i.status===c5)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.name.length?o=i.gzhead.name.charCodeAt(i.gzindex++)&255:o=0,Pt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.gzindex=0,i.status=l5)}else i.status=l5;if(i.status===l5)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.comment.length?o=i.gzhead.comment.charCodeAt(i.gzindex++)&255:o=0,Pt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.status=h5)}else i.status=h5;if(i.status===h5&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&Us(e),i.pending+2<=i.pending_buf_size&&(Pt(i,e.adler&255),Pt(i,e.adler>>8&255),e.adler=0,i.status=Tf)):i.status=Tf),i.pending!==0){if(Us(e),e.avail_out===0)return i.last_flush=-1,Qo}else if(e.avail_in===0&&VD(t)<=VD(r)&&t!==zs)return js(e,x7);if(i.status===q1&&e.avail_in!==0)return js(e,x7);if(e.avail_in!==0||i.lookahead!==0||t!==Bf&&i.status!==q1){var u=i.strategy===f5?Bae(i,t):i.strategy===pae?Rae(i,t):Hl[i.level].func(i,t);if((u===kf||u===jl)&&(i.status=q1),u===Ur||u===kf)return e.avail_out===0&&(i.last_flush=-1),Qo;if(u===U1&&(t===fae?En._tr_align(i):t!==zD&&(En._tr_stored_block(i,0,0,!1),t===cae&&(Fs(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),Us(e),e.avail_out===0))return i.last_flush=-1,Qo}return t!==zs?Qo:i.wrap<=0?KD:(i.wrap===2?(Pt(i,e.adler&255),Pt(i,e.adler>>8&255),Pt(i,e.adler>>16&255),Pt(i,e.adler>>24&255),Pt(i,e.total_in&255),Pt(i,e.total_in>>8&255),Pt(i,e.total_in>>16&255),Pt(i,e.total_in>>24&255)):(L1(i,e.adler>>>16),L1(i,e.adler&65535)),Us(e),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?Qo:KD)}function qae(e){var t;return!e||!e.state?On:(t=e.state.status,t!==p5&&t!==I7&&t!==c5&&t!==l5&&t!==h5&&t!==Tf&&t!==q1?js(e,On):(e.state=null,t===Tf?js(e,lae):Qo))}function Uae(e,t){var r=t.length,i,n,o,a,s,u,c,l;if(!e||!e.state||(i=e.state,a=i.wrap,a===2||a===1&&i.status!==p5||i.lookahead))return On;for(a===1&&(e.adler=GD(e.adler,t,r,0)),i.wrap=0,r>=i.w_size&&(a===0&&(Fs(i.head),i.strstart=0,i.block_start=0,i.insert=0),l=new Oi.Buf8(i.w_size),Oi.arraySet(l,t,r-i.w_size,i.w_size,0),t=l,r=i.w_size),s=e.avail_in,u=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,Rf(i);i.lookahead>=bt;){n=i.strstart,o=i.lookahead-(bt-1);do i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+bt-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++;while(--o);i.strstart=n,i.lookahead=bt-1,Rf(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=bt-1,i.match_available=0,e.next_in=u,e.input=c,e.avail_in=s,i.wrap=a,Qo}ea.deflateInit=Dae;ea.deflateInit2=$D;ea.deflateReset=YD;ea.deflateResetKeep=WD;ea.deflateSetHeader=Cae;ea.deflate=Lae;ea.deflateEnd=qae;ea.deflateSetDictionary=Uae;ea.deflateInfo="pako deflate (from Nodeca project)"});var QD=k((Gve,JD)=>{"use strict";v();var g5=30,Fae=12;JD.exports=function(t,r){var i,n,o,a,s,u,c,l,m,w,E,P,M,D,L,U,K,N,C,F,H,z,G,B,g;i=t.state,n=t.next_in,B=t.input,o=n+(t.avail_in-5),a=t.next_out,g=t.output,s=a-(r-t.avail_out),u=a+(t.avail_out-257),c=i.dmax,l=i.wsize,m=i.whave,w=i.wnext,E=i.window,P=i.hold,M=i.bits,D=i.lencode,L=i.distcode,U=(1<<i.lenbits)-1,K=(1<<i.distbits)-1;e:do{M<15&&(P+=B[n++]<<M,M+=8,P+=B[n++]<<M,M+=8),N=D[P&U];t:for(;;){if(C=N>>>24,P>>>=C,M-=C,C=N>>>16&255,C===0)g[a++]=N&65535;else if(C&16){F=N&65535,C&=15,C&&(M<C&&(P+=B[n++]<<M,M+=8),F+=P&(1<<C)-1,P>>>=C,M-=C),M<15&&(P+=B[n++]<<M,M+=8,P+=B[n++]<<M,M+=8),N=L[P&K];r:for(;;){if(C=N>>>24,P>>>=C,M-=C,C=N>>>16&255,C&16){if(H=N&65535,C&=15,M<C&&(P+=B[n++]<<M,M+=8,M<C&&(P+=B[n++]<<M,M+=8)),H+=P&(1<<C)-1,H>c){t.msg="invalid distance too far back",i.mode=g5;break e}if(P>>>=C,M-=C,C=a-s,H>C){if(C=H-C,C>m&&i.sane){t.msg="invalid distance too far back",i.mode=g5;break e}if(z=0,G=E,w===0){if(z+=l-C,C<F){F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}}else if(w<C){if(z+=l+w-C,C-=w,C<F){F-=C;do g[a++]=E[z++];while(--C);if(z=0,w<F){C=w,F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}}}else if(z+=w-C,C<F){F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}for(;F>2;)g[a++]=G[z++],g[a++]=G[z++],g[a++]=G[z++],F-=3;F&&(g[a++]=G[z++],F>1&&(g[a++]=G[z++]))}else{z=a-H;do g[a++]=g[z++],g[a++]=g[z++],g[a++]=g[z++],F-=3;while(F>2);F&&(g[a++]=g[z++],F>1&&(g[a++]=g[z++]))}}else if((C&64)===0){N=L[(N&65535)+(P&(1<<C)-1)];continue r}else{t.msg="invalid distance code",i.mode=g5;break e}break}}else if((C&64)===0){N=D[(N&65535)+(P&(1<<C)-1)];continue t}else if(C&32){i.mode=Fae;break e}else{t.msg="invalid literal/length code",i.mode=g5;break e}break}}while(n<o&&a<u);F=M>>3,n-=F,M-=F<<3,P&=(1<<M)-1,t.next_in=n,t.next_out=a,t.avail_in=n<o?5+(o-n):5-(n-o),t.avail_out=a<u?257+(u-a):257-(a-u),i.hold=P,i.bits=M}});var aL=k((Wve,oL)=>{"use strict";v();var eL=k1(),zl=15,tL=852,rL=592,iL=0,A7=1,nL=2,Hae=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],jae=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],zae=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Kae=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];oL.exports=function(t,r,i,n,o,a,s,u){var c=u.bits,l=0,m=0,w=0,E=0,P=0,M=0,D=0,L=0,U=0,K=0,N,C,F,H,z,G=null,B=0,g,O=new eL.Buf16(zl+1),y=new eL.Buf16(zl+1),f=null,d=0,_,x,b;for(l=0;l<=zl;l++)O[l]=0;for(m=0;m<n;m++)O[r[i+m]]++;for(P=c,E=zl;E>=1&&O[E]===0;E--);if(P>E&&(P=E),E===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,u.bits=1,0;for(w=1;w<E&&O[w]===0;w++);for(P<w&&(P=w),L=1,l=1;l<=zl;l++)if(L<<=1,L-=O[l],L<0)return-1;if(L>0&&(t===iL||E!==1))return-1;for(y[1]=0,l=1;l<zl;l++)y[l+1]=y[l]+O[l];for(m=0;m<n;m++)r[i+m]!==0&&(s[y[r[i+m]]++]=m);if(t===iL?(G=f=s,g=19):t===A7?(G=Hae,B-=257,f=jae,d-=257,g=256):(G=zae,f=Kae,g=-1),K=0,m=0,l=w,z=a,M=P,D=0,F=-1,U=1<<P,H=U-1,t===A7&&U>tL||t===nL&&U>rL)return 1;for(;;){_=l-D,s[m]<g?(x=0,b=s[m]):s[m]>g?(x=f[d+s[m]],b=G[B+s[m]]):(x=96,b=0),N=1<<l-D,C=1<<M,w=C;do C-=N,o[z+(K>>D)+C]=_<<24|x<<16|b|0;while(C!==0);for(N=1<<l-1;K&N;)N>>=1;if(N!==0?(K&=N-1,K+=N):K=0,m++,--O[l]===0){if(l===E)break;l=r[i+s[m]]}if(l>P&&(K&H)!==F){for(D===0&&(D=P),z+=w,M=l-D,L=1<<M;M+D<E&&(L-=O[M+D],!(L<=0));)M++,L<<=1;if(U+=1<<M,t===A7&&U>tL||t===nL&&U>rL)return 1;F=K&H,o[F]=P<<24|M<<16|z-a|0}}return K!==0&&(o[z+K]=l-D<<24|64<<16|0),u.bits=P,0}});var HL=k(uo=>{"use strict";v();var Wi=k1(),M7=w7(),ta=S7(),Vae=QD(),F1=aL(),Gae=0,BL=1,ML=2,sL=4,Zae=5,v5=6,Mf=0,Wae=1,Yae=2,In=-2,NL=-3,N7=-4,$ae=-5,uL=8,CL=1,fL=2,cL=3,lL=4,hL=5,dL=6,pL=7,gL=8,vL=9,mL=10,b5=11,Qa=12,P7=13,yL=14,T7=15,bL=16,_L=17,wL=18,SL=19,m5=20,y5=21,xL=22,EL=23,OL=24,IL=25,AL=26,k7=27,PL=28,TL=29,rr=30,C7=31,Xae=32,Jae=852,Qae=592,ese=15,tse=ese;function kL(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function rse(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Wi.Buf16(320),this.work=new Wi.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function DL(e){var t;return!e||!e.state?In:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=CL,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Wi.Buf32(Jae),t.distcode=t.distdyn=new Wi.Buf32(Qae),t.sane=1,t.back=-1,Mf)}function LL(e){var t;return!e||!e.state?In:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,DL(e))}function qL(e,t){var r,i;return!e||!e.state||(i=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?In:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,LL(e))}function UL(e,t){var r,i;return e?(i=new rse,e.state=i,i.window=null,r=qL(e,t),r!==Mf&&(e.state=null),r):In}function ise(e){return UL(e,tse)}var RL=!0,R7,B7;function nse(e){if(RL){var t;for(R7=new Wi.Buf32(512),B7=new Wi.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(F1(BL,e.lens,0,288,R7,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;F1(ML,e.lens,0,32,B7,0,e.work,{bits:5}),RL=!1}e.lencode=R7,e.lenbits=9,e.distcode=B7,e.distbits=5}function FL(e,t,r,i){var n,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Wi.Buf8(o.wsize)),i>=o.wsize?(Wi.arraySet(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),Wi.arraySet(o.window,t,r-i,n,o.wnext),i-=n,i?(Wi.arraySet(o.window,t,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function ose(e,t){var r,i,n,o,a,s,u,c,l,m,w,E,P,M,D=0,L,U,K,N,C,F,H,z,G=new Wi.Buf8(4),B,g,O=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return In;r=e.state,r.mode===Qa&&(r.mode=P7),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,m=s,w=u,z=Mf;e:for(;;)switch(r.mode){case CL:if(r.wrap===0){r.mode=P7;break}for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.wrap&2&&c===35615){r.check=0,G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0),c=0,l=0,r.mode=fL;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=rr;break}if((c&15)!==uL){e.msg="unknown compression method",r.mode=rr;break}if(c>>>=4,l-=4,H=(c&15)+8,r.wbits===0)r.wbits=H;else if(H>r.wbits){e.msg="invalid window size",r.mode=rr;break}r.dmax=1<<H,e.adler=r.check=1,r.mode=c&512?mL:Qa,c=0,l=0;break;case fL:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.flags=c,(r.flags&255)!==uL){e.msg="unknown compression method",r.mode=rr;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=rr;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0,r.mode=cL;case cL:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.time=c),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,G[2]=c>>>16&255,G[3]=c>>>24&255,r.check=ta(r.check,G,4,0)),c=0,l=0,r.mode=lL;case lL:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0,r.mode=hL;case hL:if(r.flags&1024){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0}else r.head&&(r.head.extra=null);r.mode=dL;case dL:if(r.flags&1024&&(E=r.length,E>s&&(E=s),E&&(r.head&&(H=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Wi.arraySet(r.head.extra,i,o,E,H)),r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,r.length-=E),r.length))break e;r.length=0,r.mode=pL;case pL:if(r.flags&2048){if(s===0)break e;E=0;do H=i[o+E++],r.head&&H&&r.length<65536&&(r.head.name+=String.fromCharCode(H));while(H&&E<s);if(r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,H)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=gL;case gL:if(r.flags&4096){if(s===0)break e;E=0;do H=i[o+E++],r.head&&H&&r.length<65536&&(r.head.comment+=String.fromCharCode(H));while(H&&E<s);if(r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,H)break e}else r.head&&(r.head.comment=null);r.mode=vL;case vL:if(r.flags&512){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=rr;break}c=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Qa;break;case mL:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}e.adler=r.check=kL(c),c=0,l=0,r.mode=b5;case b5:if(r.havedict===0)return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,Yae;e.adler=r.check=1,r.mode=Qa;case Qa:if(t===Zae||t===v5)break e;case P7:if(r.last){c>>>=l&7,l-=l&7,r.mode=k7;break}for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}switch(r.last=c&1,c>>>=1,l-=1,c&3){case 0:r.mode=yL;break;case 1:if(nse(r),r.mode=m5,t===v5){c>>>=2,l-=2;break e}break;case 2:r.mode=_L;break;case 3:e.msg="invalid block type",r.mode=rr}c>>>=2,l-=2;break;case yL:for(c>>>=l&7,l-=l&7;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=rr;break}if(r.length=c&65535,c=0,l=0,r.mode=T7,t===v5)break e;case T7:r.mode=bL;case bL:if(E=r.length,E){if(E>s&&(E=s),E>u&&(E=u),E===0)break e;Wi.arraySet(n,i,o,E,a),s-=E,o+=E,u-=E,a+=E,r.length-=E;break}r.mode=Qa;break;case _L:for(;l<14;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.nlen=(c&31)+257,c>>>=5,l-=5,r.ndist=(c&31)+1,c>>>=5,l-=5,r.ncode=(c&15)+4,c>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=rr;break}r.have=0,r.mode=wL;case wL:for(;r.have<r.ncode;){for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.lens[O[r.have++]]=c&7,c>>>=3,l-=3}for(;r.have<19;)r.lens[O[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,B={bits:r.lenbits},z=F1(Gae,r.lens,0,19,r.lencode,0,r.work,B),r.lenbits=B.bits,z){e.msg="invalid code lengths set",r.mode=rr;break}r.have=0,r.mode=SL;case SL:for(;r.have<r.nlen+r.ndist;){for(;D=r.lencode[c&(1<<r.lenbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(K<16)c>>>=L,l-=L,r.lens[r.have++]=K;else{if(K===16){for(g=L+2;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c>>>=L,l-=L,r.have===0){e.msg="invalid bit length repeat",r.mode=rr;break}H=r.lens[r.have-1],E=3+(c&3),c>>>=2,l-=2}else if(K===17){for(g=L+3;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=L,l-=L,H=0,E=3+(c&7),c>>>=3,l-=3}else{for(g=L+7;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=L,l-=L,H=0,E=11+(c&127),c>>>=7,l-=7}if(r.have+E>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=rr;break}for(;E--;)r.lens[r.have++]=H}}if(r.mode===rr)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=rr;break}if(r.lenbits=9,B={bits:r.lenbits},z=F1(BL,r.lens,0,r.nlen,r.lencode,0,r.work,B),r.lenbits=B.bits,z){e.msg="invalid literal/lengths set",r.mode=rr;break}if(r.distbits=6,r.distcode=r.distdyn,B={bits:r.distbits},z=F1(ML,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,B),r.distbits=B.bits,z){e.msg="invalid distances set",r.mode=rr;break}if(r.mode=m5,t===v5)break e;case m5:r.mode=y5;case y5:if(s>=6&&u>=258){e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,Vae(e,w),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,r.mode===Qa&&(r.back=-1);break}for(r.back=0;D=r.lencode[c&(1<<r.lenbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(U&&(U&240)===0){for(N=L,C=U,F=K;D=r.lencode[F+((c&(1<<N+C)-1)>>N)],L=D>>>24,U=D>>>16&255,K=D&65535,!(N+L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=N,l-=N,r.back+=N}if(c>>>=L,l-=L,r.back+=L,r.length=K,U===0){r.mode=AL;break}if(U&32){r.back=-1,r.mode=Qa;break}if(U&64){e.msg="invalid literal/length code",r.mode=rr;break}r.extra=U&15,r.mode=xL;case xL:if(r.extra){for(g=r.extra;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=EL;case EL:for(;D=r.distcode[c&(1<<r.distbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((U&240)===0){for(N=L,C=U,F=K;D=r.distcode[F+((c&(1<<N+C)-1)>>N)],L=D>>>24,U=D>>>16&255,K=D&65535,!(N+L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=N,l-=N,r.back+=N}if(c>>>=L,l-=L,r.back+=L,U&64){e.msg="invalid distance code",r.mode=rr;break}r.offset=K,r.extra=U&15,r.mode=OL;case OL:if(r.extra){for(g=r.extra;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=rr;break}r.mode=IL;case IL:if(u===0)break e;if(E=w-u,r.offset>E){if(E=r.offset-E,E>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=rr;break}E>r.wnext?(E-=r.wnext,P=r.wsize-E):P=r.wnext-E,E>r.length&&(E=r.length),M=r.window}else M=n,P=a-r.offset,E=r.length;E>u&&(E=u),u-=E,r.length-=E;do n[a++]=M[P++];while(--E);r.length===0&&(r.mode=y5);break;case AL:if(u===0)break e;n[a++]=r.length,u--,r.mode=y5;break;case k7:if(r.wrap){for(;l<32;){if(s===0)break e;s--,c|=i[o++]<<l,l+=8}if(w-=u,e.total_out+=w,r.total+=w,w&&(e.adler=r.check=r.flags?ta(r.check,n,w,a-w):M7(r.check,n,w,a-w)),w=u,(r.flags?c:kL(c))!==r.check){e.msg="incorrect data check",r.mode=rr;break}c=0,l=0}r.mode=PL;case PL:if(r.wrap&&r.flags){for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=rr;break}c=0,l=0}r.mode=TL;case TL:z=Wae;break e;case rr:z=NL;break e;case C7:return N7;case Xae:default:return In}return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,(r.wsize||w!==e.avail_out&&r.mode<rr&&(r.mode<k7||t!==sL))&&FL(e,e.output,e.next_out,w-e.avail_out)?(r.mode=C7,N7):(m-=e.avail_in,w-=e.avail_out,e.total_in+=m,e.total_out+=w,r.total+=w,r.wrap&&w&&(e.adler=r.check=r.flags?ta(r.check,n,w,e.next_out-w):M7(r.check,n,w,e.next_out-w)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Qa?128:0)+(r.mode===m5||r.mode===T7?256:0),(m===0&&w===0||t===sL)&&z===Mf&&(z=$ae),z)}function ase(e){if(!e||!e.state)return In;var t=e.state;return t.window&&(t.window=null),e.state=null,Mf}function sse(e,t){var r;return!e||!e.state||(r=e.state,(r.wrap&2)===0)?In:(r.head=t,t.done=!1,Mf)}function use(e,t){var r=t.length,i,n,o;return!e||!e.state||(i=e.state,i.wrap!==0&&i.mode!==b5)?In:i.mode===b5&&(n=1,n=M7(n,t,r,0),n!==i.check)?NL:(o=FL(e,t,r,r),o?(i.mode=C7,N7):(i.havedict=1,Mf))}uo.inflateReset=LL;uo.inflateReset2=qL;uo.inflateResetKeep=DL;uo.inflateInit=ise;uo.inflateInit2=UL;uo.inflate=ose;uo.inflateEnd=ase;uo.inflateGetHeader=sse;uo.inflateSetDictionary=use;uo.inflateInfo="pako inflate (from Nodeca project)"});var zL=k((Jve,jL)=>{"use strict";v();jL.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var VL=k(de=>{"use strict";v();var Yi=Es(),fse=gD(),H1=XD(),Nf=HL(),KL=zL();for(D7 in KL)de[D7]=KL[D7];var D7;de.NONE=0;de.DEFLATE=1;de.INFLATE=2;de.GZIP=3;de.GUNZIP=4;de.DEFLATERAW=5;de.INFLATERAW=6;de.UNZIP=7;var cse=31,lse=139;function mi(e){if(typeof e!="number"||e<de.DEFLATE||e>de.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}mi.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,Yi(this.init_done,"close before init"),Yi(this.mode<=de.UNZIP),this.mode===de.DEFLATE||this.mode===de.GZIP||this.mode===de.DEFLATERAW?H1.deflateEnd(this.strm):(this.mode===de.INFLATE||this.mode===de.GUNZIP||this.mode===de.INFLATERAW||this.mode===de.UNZIP)&&Nf.inflateEnd(this.strm),this.mode=de.NONE,this.dictionary=null};mi.prototype.write=function(e,t,r,i,n,o,a){return this._write(!0,e,t,r,i,n,o,a)};mi.prototype.writeSync=function(e,t,r,i,n,o,a){return this._write(!1,e,t,r,i,n,o,a)};mi.prototype._write=function(e,t,r,i,n,o,a,s){if(Yi.equal(arguments.length,8),Yi(this.init_done,"write before init"),Yi(this.mode!==de.NONE,"already finalized"),Yi.equal(!1,this.write_in_progress,"write already in progress"),Yi.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,Yi.equal(!1,t===void 0,"must provide flush value"),this.write_in_progress=!0,t!==de.Z_NO_FLUSH&&t!==de.Z_PARTIAL_FLUSH&&t!==de.Z_SYNC_FLUSH&&t!==de.Z_FULL_FLUSH&&t!==de.Z_FINISH&&t!==de.Z_BLOCK)throw new Error("Invalid flush value");if(r==null&&(r=h.Buffer.alloc(0),n=0,i=0),this.strm.avail_in=n,this.strm.input=r,this.strm.next_in=i,this.strm.avail_out=s,this.strm.output=o,this.strm.next_out=a,this.flush=t,!e)return this._process(),this._checkError()?this._afterSync():void 0;var u=this;return A.default.nextTick(function(){u._process(),u._after()}),this};mi.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]};mi.prototype._process=function(){var e=null;switch(this.mode){case de.DEFLATE:case de.GZIP:case de.DEFLATERAW:this.err=H1.deflate(this.strm,this.flush);break;case de.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(e===null)break;if(this.strm.input[e]===cse){if(this.gzip_id_bytes_read=1,e++,this.strm.avail_in===1)break}else{this.mode=de.INFLATE;break}case 1:if(e===null)break;this.strm.input[e]===lse?(this.gzip_id_bytes_read=2,this.mode=de.GUNZIP):this.mode=de.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case de.INFLATE:case de.GUNZIP:case de.INFLATERAW:for(this.err=Nf.inflate(this.strm,this.flush),this.err===de.Z_NEED_DICT&&this.dictionary&&(this.err=Nf.inflateSetDictionary(this.strm,this.dictionary),this.err===de.Z_OK?this.err=Nf.inflate(this.strm,this.flush):this.err===de.Z_DATA_ERROR&&(this.err=de.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===de.GUNZIP&&this.err===de.Z_STREAM_END&&this.strm.next_in[0]!==0;)this.reset(),this.err=Nf.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}};mi.prototype._checkError=function(){switch(this.err){case de.Z_OK:case de.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===de.Z_FINISH)return this._error("unexpected end of file"),!1;break;case de.Z_STREAM_END:break;case de.Z_NEED_DICT:return this.dictionary==null?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0};mi.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}};mi.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()};mi.prototype.init=function(e,t,r,i,n){Yi(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),Yi(e>=8&&e<=15,"invalid windowBits"),Yi(t>=-1&&t<=9,"invalid compression level"),Yi(r>=1&&r<=9,"invalid memlevel"),Yi(i===de.Z_FILTERED||i===de.Z_HUFFMAN_ONLY||i===de.Z_RLE||i===de.Z_FIXED||i===de.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(t,e,r,i,n),this._setDictionary()};mi.prototype.params=function(){throw new Error("deflateParams Not supported")};mi.prototype.reset=function(){this._reset(),this._setDictionary()};mi.prototype._init=function(e,t,r,i,n){switch(this.level=e,this.windowBits=t,this.memLevel=r,this.strategy=i,this.flush=de.Z_NO_FLUSH,this.err=de.Z_OK,(this.mode===de.GZIP||this.mode===de.GUNZIP)&&(this.windowBits+=16),this.mode===de.UNZIP&&(this.windowBits+=32),(this.mode===de.DEFLATERAW||this.mode===de.INFLATERAW)&&(this.windowBits=-1*this.windowBits),this.strm=new fse,this.mode){case de.DEFLATE:case de.GZIP:case de.DEFLATERAW:this.err=H1.deflateInit2(this.strm,this.level,de.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case de.INFLATE:case de.GUNZIP:case de.INFLATERAW:case de.UNZIP:this.err=Nf.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==de.Z_OK&&this._error("Init error"),this.dictionary=n,this.write_in_progress=!1,this.init_done=!0};mi.prototype._setDictionary=function(){if(this.dictionary!=null){switch(this.err=de.Z_OK,this.mode){case de.DEFLATE:case de.DEFLATERAW:this.err=H1.deflateSetDictionary(this.strm,this.dictionary);break;default:break}this.err!==de.Z_OK&&this._error("Failed to set dictionary")}};mi.prototype._reset=function(){switch(this.err=de.Z_OK,this.mode){case de.DEFLATE:case de.DEFLATERAW:case de.GZIP:this.err=H1.deflateReset(this.strm);break;case de.INFLATE:case de.INFLATERAW:case de.GUNZIP:this.err=Nf.inflateReset(this.strm);break;default:break}this.err!==de.Z_OK&&this._error("Failed to reset stream")};de.Zlib=mi});var U7=k(we=>{"use strict";v();var ra=Kt().Buffer,YL=t2().Transform,De=VL(),Ks=rn(),j1=Es().ok,q7=Kt().kMaxLength,$L="Cannot create final Buffer. It would be larger than 0x"+q7.toString(16)+" bytes";De.Z_MIN_WINDOWBITS=8;De.Z_MAX_WINDOWBITS=15;De.Z_DEFAULT_WINDOWBITS=15;De.Z_MIN_CHUNK=64;De.Z_MAX_CHUNK=1/0;De.Z_DEFAULT_CHUNK=16*1024;De.Z_MIN_MEMLEVEL=1;De.Z_MAX_MEMLEVEL=9;De.Z_DEFAULT_MEMLEVEL=8;De.Z_MIN_LEVEL=-1;De.Z_MAX_LEVEL=9;De.Z_DEFAULT_LEVEL=De.Z_DEFAULT_COMPRESSION;var GL=Object.keys(De);for(_5=0;_5<GL.length;_5++)w5=GL[_5],w5.match(/^Z/)&&Object.defineProperty(we,w5,{enumerable:!0,value:De[w5],writable:!1});var w5,_5,x5={Z_OK:De.Z_OK,Z_STREAM_END:De.Z_STREAM_END,Z_NEED_DICT:De.Z_NEED_DICT,Z_ERRNO:De.Z_ERRNO,Z_STREAM_ERROR:De.Z_STREAM_ERROR,Z_DATA_ERROR:De.Z_DATA_ERROR,Z_MEM_ERROR:De.Z_MEM_ERROR,Z_BUF_ERROR:De.Z_BUF_ERROR,Z_VERSION_ERROR:De.Z_VERSION_ERROR},ZL=Object.keys(x5);for(S5=0;S5<ZL.length;S5++)L7=ZL[S5],x5[x5[L7]]=L7;var L7,S5;Object.defineProperty(we,"codes",{enumerable:!0,value:Object.freeze(x5),writable:!1});we.Deflate=Cf;we.Inflate=Df;we.Gzip=Lf;we.Gunzip=qf;we.DeflateRaw=Uf;we.InflateRaw=Ff;we.Unzip=Hf;we.createDeflate=function(e){return new Cf(e)};we.createInflate=function(e){return new Df(e)};we.createDeflateRaw=function(e){return new Uf(e)};we.createInflateRaw=function(e){return new Ff(e)};we.createGzip=function(e){return new Lf(e)};we.createGunzip=function(e){return new qf(e)};we.createUnzip=function(e){return new Hf(e)};we.deflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Cf(t),e,r)};we.deflateSync=function(e,t){return zf(new Cf(t),e)};we.gzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Lf(t),e,r)};we.gzipSync=function(e,t){return zf(new Lf(t),e)};we.deflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Uf(t),e,r)};we.deflateRawSync=function(e,t){return zf(new Uf(t),e)};we.unzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Hf(t),e,r)};we.unzipSync=function(e,t){return zf(new Hf(t),e)};we.inflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Df(t),e,r)};we.inflateSync=function(e,t){return zf(new Df(t),e)};we.gunzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new qf(t),e,r)};we.gunzipSync=function(e,t){return zf(new qf(t),e)};we.inflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Ff(t),e,r)};we.inflateRawSync=function(e,t){return zf(new Ff(t),e)};function jf(e,t,r){var i=[],n=0;e.on("error",a),e.on("end",s),e.end(t),o();function o(){for(var u;(u=e.read())!==null;)i.push(u),n+=u.length;e.once("readable",o)}function a(u){e.removeListener("end",s),e.removeListener("readable",o),r(u)}function s(){var u,c=null;n>=q7?c=new RangeError($L):u=ra.concat(i,n),i=[],e.close(),r(c,u)}}function zf(e,t){if(typeof t=="string"&&(t=ra.from(t)),!ra.isBuffer(t))throw new TypeError("Not a string or buffer");var r=e._finishFlushFlag;return e._processChunk(t,r)}function Cf(e){if(!(this instanceof Cf))return new Cf(e);hr.call(this,e,De.DEFLATE)}function Df(e){if(!(this instanceof Df))return new Df(e);hr.call(this,e,De.INFLATE)}function Lf(e){if(!(this instanceof Lf))return new Lf(e);hr.call(this,e,De.GZIP)}function qf(e){if(!(this instanceof qf))return new qf(e);hr.call(this,e,De.GUNZIP)}function Uf(e){if(!(this instanceof Uf))return new Uf(e);hr.call(this,e,De.DEFLATERAW)}function Ff(e){if(!(this instanceof Ff))return new Ff(e);hr.call(this,e,De.INFLATERAW)}function Hf(e){if(!(this instanceof Hf))return new Hf(e);hr.call(this,e,De.UNZIP)}function WL(e){return e===De.Z_NO_FLUSH||e===De.Z_PARTIAL_FLUSH||e===De.Z_SYNC_FLUSH||e===De.Z_FULL_FLUSH||e===De.Z_FINISH||e===De.Z_BLOCK}function hr(e,t){var r=this;if(this._opts=e=e||{},this._chunkSize=e.chunkSize||we.Z_DEFAULT_CHUNK,YL.call(this,e),e.flush&&!WL(e.flush))throw new Error("Invalid flush flag: "+e.flush);if(e.finishFlush&&!WL(e.finishFlush))throw new Error("Invalid flush flag: "+e.finishFlush);if(this._flushFlag=e.flush||De.Z_NO_FLUSH,this._finishFlushFlag=typeof e.finishFlush<"u"?e.finishFlush:De.Z_FINISH,e.chunkSize&&(e.chunkSize<we.Z_MIN_CHUNK||e.chunkSize>we.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<we.Z_MIN_WINDOWBITS||e.windowBits>we.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<we.Z_MIN_LEVEL||e.level>we.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<we.Z_MIN_MEMLEVEL||e.memLevel>we.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=we.Z_FILTERED&&e.strategy!=we.Z_HUFFMAN_ONLY&&e.strategy!=we.Z_RLE&&e.strategy!=we.Z_FIXED&&e.strategy!=we.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!ra.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new De.Zlib(t);var i=this;this._hadError=!1,this._handle.onerror=function(a,s){E5(i),i._hadError=!0;var u=new Error(a);u.errno=s,u.code=we.codes[s],i.emit("error",u)};var n=we.Z_DEFAULT_COMPRESSION;typeof e.level=="number"&&(n=e.level);var o=we.Z_DEFAULT_STRATEGY;typeof e.strategy=="number"&&(o=e.strategy),this._handle.init(e.windowBits||we.Z_DEFAULT_WINDOWBITS,n,e.memLevel||we.Z_DEFAULT_MEMLEVEL,o,e.dictionary),this._buffer=ra.allocUnsafe(this._chunkSize),this._offset=0,this._level=n,this._strategy=o,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!r._handle},configurable:!0,enumerable:!0})}Ks.inherits(hr,YL);hr.prototype.params=function(e,t,r){if(e<we.Z_MIN_LEVEL||e>we.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=we.Z_FILTERED&&t!=we.Z_HUFFMAN_ONLY&&t!=we.Z_RLE&&t!=we.Z_FIXED&&t!=we.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var i=this;this.flush(De.Z_SYNC_FLUSH,function(){j1(i._handle,"zlib binding closed"),i._handle.params(e,t),i._hadError||(i._level=e,i._strategy=t,r&&r())})}else A.default.nextTick(r)};hr.prototype.reset=function(){return j1(this._handle,"zlib binding closed"),this._handle.reset()};hr.prototype._flush=function(e){this._transform(ra.alloc(0),"",e)};hr.prototype.flush=function(e,t){var r=this,i=this._writableState;(typeof e=="function"||e===void 0&&!t)&&(t=e,e=De.Z_FULL_FLUSH),i.ended?t&&A.default.nextTick(t):i.ending?t&&this.once("end",t):i.needDrain?t&&this.once("drain",function(){return r.flush(e,t)}):(this._flushFlag=e,this.write(ra.alloc(0),"",t))};hr.prototype.close=function(e){E5(this,e),A.default.nextTick(hse,this)};function E5(e,t){t&&A.default.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}function hse(e){e.emit("close")}hr.prototype._transform=function(e,t,r){var i,n=this._writableState,o=n.ending||n.ended,a=o&&(!e||n.length===e.length);if(e!==null&&!ra.isBuffer(e))return r(new Error("invalid input"));if(!this._handle)return r(new Error("zlib binding closed"));a?i=this._finishFlushFlag:(i=this._flushFlag,e.length>=n.length&&(this._flushFlag=this._opts.flush||De.Z_NO_FLUSH)),this._processChunk(e,i,r)};hr.prototype._processChunk=function(e,t,r){var i=e&&e.length,n=this._chunkSize-this._offset,o=0,a=this,s=typeof r=="function";if(!s){var u=[],c=0,l;this.on("error",function(M){l=M}),j1(this._handle,"zlib binding closed");do var m=this._handle.writeSync(t,e,o,i,this._buffer,this._offset,n);while(!this._hadError&&P(m[0],m[1]));if(this._hadError)throw l;if(c>=q7)throw E5(this),new RangeError($L);var w=ra.concat(u,c);return E5(this),w}j1(this._handle,"zlib binding closed");var E=this._handle.write(t,e,o,i,this._buffer,this._offset,n);E.buffer=e,E.callback=P;function P(M,D){if(this&&(this.buffer=null,this.callback=null),!a._hadError){var L=n-D;if(j1(L>=0,"have should not go down"),L>0){var U=a._buffer.slice(a._offset,a._offset+L);a._offset+=L,s?a.push(U):(u.push(U),c+=U.length)}if((D===0||a._offset>=a._chunkSize)&&(n=a._chunkSize,a._offset=0,a._buffer=ra.allocUnsafe(a._chunkSize)),D===0){if(o+=i-M,i=M,!s)return!0;var K=a._handle.write(t,e,o,i,a._buffer,a._offset,a._chunkSize);K.callback=P,K.buffer=e;return}if(!s)return!1;r()}}};Ks.inherits(Cf,hr);Ks.inherits(Df,hr);Ks.inherits(Lf,hr);Ks.inherits(qf,hr);Ks.inherits(Uf,hr);Ks.inherits(Ff,hr);Ks.inherits(Hf,hr)});var tq=k((ome,eq)=>{"use strict";v();var F7=c7(),nme=_r(),XL=U7(),dse=8*1024*1024;function JL(e,t){var r=t&&t.maxDecompressedBytes||dse;return XL.gunzipSync(h.Buffer.from(e,"base64"),{maxOutputLength:r})}async function QL(e,t){if(!t.expectedIssuerDid)throw new Error("expectedIssuerDid is required to verify a status list (issuer pinning); refusing to read revocation state from an unpinned/unverified JWT");var r=t.didResolver;if(!r){var i=t.issuerJwks||(t.issuerPublicJwk?{keys:[t.issuerPublicJwk]}:null);if(!i)throw new Error("Provide params.didResolver, params.issuerJwks, or params.issuerPublicJwk to verify the status list signature");r=async function(){return{jwks:i}}}var n=await F7.verifyVcJwt(e,{didResolver:r,expectedIssuerDid:t.expectedIssuerDid,allowedAlgs:t.allowedAlgs,allowLegacyDER:t.allowLegacyDER,clockToleranceSec:t.clockToleranceSec});if(!n.valid)throw new Error("Status list signature verification failed: "+(n.error||"invalid signature"));return n.payload}async function pse(e){if(!e.issuerDid||!e.privateJwk)throw new Error("issuerDid and privateJwk are required");var t=e.listId||e.issuerDid+"/status/"+Date.now(),r=e.listSize||1e5,i=Math.ceil(r/8),n=h.Buffer.alloc(i,0),o=U7(),a=o.gzipSync(n),s=a.toString("base64"),u={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],type:["VerifiableCredential","StatusList2021Credential"],issuer:e.issuerDid,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,type:"StatusList2021",statusPurpose:"revocation",encodedList:s}},c=await F7.issueVcJwt({issuerDid:e.issuerDid,subjectId:t,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:u.credentialSubject,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:c.jwt,listId:t}}async function gse(e){if(!e.listVcJwt||e.index===void 0||!e.status||!e.privateJwk)throw new Error("listVcJwt, index, status, and privateJwk are required");var t=await QL(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=JL(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=e.status==="revoked"||e.status==="suspended"?1:0;a===1?i[n]|=1<<o:i[n]&=~(1<<o);var s=XL.gzipSync(i),u=s.toString("base64"),c={id:t.vc.credentialSubject.id,type:"StatusList2021",statusPurpose:"revocation",encodedList:u},l=await F7.issueVcJwt({issuerDid:t.iss,subjectId:t.vc.credentialSubject.id,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:c,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:l.jwt}}async function vse(e){if(!e.listVcJwt||e.index===void 0)throw new Error("listVcJwt and index are required");var t=await QL(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=JL(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=i[n]>>o&1;return a===1?"revoked":"valid"}eq.exports={createStatusList:pse,updateStatusList:gse,getCredentialStatusEntry:vse}});var nq=k((sme,iq)=>{"use strict";v();var mse=_r();function rq(e){var t;if(typeof e=="string")t=h.Buffer.from(e,"utf8");else if(h.Buffer.isBuffer(e))t=e;else if(e instanceof Uint8Array)t=h.Buffer.from(e);else throw new Error("Data must be string, Buffer, or Uint8Array");return mse.createHash("sha256").update(t).digest("hex")}function yse(e){if(!e.kind||!e.hash||!e.issuerDid)throw new Error("kind, hash, and issuerDid are required");var t=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];if(t.indexOf(e.kind)===-1)throw new Error("Invalid kind. Must be one of: "+t.join(", "));if(!/^[a-fA-F0-9]{64}$/.test(e.hash))throw new Error("Invalid hash format. Must be 64 hex characters");var r={protocol:"SmartLedger",version:"1.0",type:e.kind,hash:e.hash,issuer:e.issuerDid,timestamp:e.issuedAt||new Date().toISOString()};return{json:JSON.stringify(r)}}function bse(e,t){var r=rq(e);return r===t}function _se(e){try{var t=JSON.parse(e);if(t.protocol!=="SmartLedger")return{valid:!1,error:"Invalid protocol"};var r=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];return r.indexOf(t.type)===-1?{valid:!1,error:"Invalid anchor type"}:/^[a-fA-F0-9]{64}$/.test(t.hash)?{valid:!0,protocol:t.protocol,version:t.version,type:t.type,hash:t.hash,issuer:t.issuer,timestamp:t.timestamp}:{valid:!1,error:"Invalid hash format"}}catch(i){return{valid:!1,error:"Failed to parse anchor payload: "+i.message}}}iq.exports={sha256Hex:rq,buildAnchorPayload:yse,verifyAnchorHash:bse,parseAnchorPayload:_se}});var z1=k((fme,aq)=>{"use strict";v();var oq=ds();function wse(){var e=oq.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function Sse(e){return oq.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}aq.exports={uuid4:wse,randomHex:Sse}});var lq=k((hme,cq)=>{"use strict";v();var ia=Te(),H7=ia.crypto.Hash,j7=ia.crypto.ECDSA,sq=ia.crypto.Signature,z7=ia.PrivateKey,Tr=ia.util.preconditions,lme=xt(),xse=z1();function uq(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof ia.PublicKey?t.issuerPublicKey:ia.PublicKey.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?ia.PublicKey.fromString(i):null}catch{return null}}var Kl={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},fq={create:function(e,t,r,i,n,o){o=o||{},Tr.checkArgument(typeof e=="string","Right type must be string"),Tr.checkArgument(typeof t=="string","Issuer DID must be string"),Tr.checkArgument(typeof r=="string","Subject DID must be string"),Tr.checkArgument(i&&typeof i=="object","Claim must be object");var a=Object.values(Kl);Tr.checkArgument(a.includes(e),"Invalid right type: "+e);var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:i,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(s.credentialSubject.metadata=o.metadata),s},prepareRightToken:function(e,t,r,i,n,o){o=o||{},Tr.checkArgument(typeof e=="string","Right type must be string"),Tr.checkArgument(typeof t=="string","Issuer DID must be string"),Tr.checkArgument(typeof r=="string","Subject DID must be string"),Tr.checkArgument(i&&typeof i=="object","Claim must be object"),Tr.checkArgument(n instanceof z7,"Invalid issuer private key");var a=Object.values(Kl);Tr.checkArgument(a.includes(e),"Invalid right type: "+e);try{var s=this.create(e,t,r,i,n,o),u=this._signToken(s,n);return{success:!0,rightToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:u,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,subject:r,issuedAt:u.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:u.id,issuer:t,subject:r,rightType:e}}}}}catch(c){return{success:!1,error:c.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:n.rightType,issuer:n.issuerDID,subject:n.subjectDID,result:n.valid,verifiedAt:n.verifiedAt}},updateTokenStatus:n.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:n.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,i){i=i||{},Tr.checkArgument(e&&typeof e=="object","Invalid token"),Tr.checkArgument(typeof t=="string","New owner DID must be string"),Tr.checkArgument(r instanceof z7,"Invalid current owner key");try{var n=this.prepareRightTokenVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+n.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,a=uq({issuer:o},{issuerPublicKey:i.currentOwnerPublicKey});if(!a)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==a.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:i.reason||"ownership_transfer",consideration:i.consideration||null}},u=this._signToken(s,r),c=JSON.parse(JSON.stringify(e));c.id="urn:uuid:"+this._generateUUID(),c.issuanceDate=new Date().toISOString(),c.credentialSubject.id=t,c.credentialSubject.transferHistory=c.credentialSubject.transferHistory||[],c.credentialSubject.transferHistory.push({transferId:u.id,transferDate:u.issuanceDate,from:e.credentialSubject.id,to:t}),delete c.proof;var l=this._signToken(c,r);return{success:!0,newToken:l,transferProof:u,transferId:u.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:l.id,transferProof:u,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:u.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:u.id,transferDate:u.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:l.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:l.id,transferId:u.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:u.issuanceDate}}}}}catch(m){return{success:!1,error:m.message}}},prepareObligationToken:function(e,t,r,i){Tr.checkArgument(e&&typeof e=="object","Invalid right token"),Tr.checkArgument(typeof t=="string","Obligor DID must be string"),Tr.checkArgument(r&&typeof r=="object","Obligation must be object"),Tr.checkArgument(i instanceof z7,"Invalid issuer key");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(n,i);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(a){return{success:!1,error:a.message}}},prepareRightTypeValidation:function(e){Tr.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(Kl),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return Kl},verifyToken:function(e,t){var r=[];try{if(Tr.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var i=t instanceof ia.PublicKey?t:ia.PublicKey.fromString(t),n=this._canonicalizeToken(e),o=H7.sha256(h.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var a=e.proof.jws.split(".");if(a.length!==3||!a[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var s=sq.fromDER(h.Buffer.from(a[2],"base64url")),u=new j7;return u.hashbuf=o,u.sig=s,u.pubkey=i,u.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(c){return r.push(c.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=H7.sha256(h.Buffer.from(r)),n=new j7;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=t.toDER().toString("base64url");return i+".."+n},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=H7.sha256(h.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=uq(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=sq.fromDER(h.Buffer.from(a[2],"base64url")),u=new j7;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);i<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var a=new Date(e.credentialSubject.validUntil);i>a&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(Kl);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return xse.uuid4()}};fq.RightTypes=Kl;cq.exports=fq});var pq=k((pme,dq)=>{"use strict";v();var hq=Te(),K1=hq.crypto.Hash,$i=hq.util.preconditions,Ese=z1(),Kf={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},Ose={prepareClaimValidation:function(e,t){try{$i.checkArgument(e&&typeof e=="object","Invalid claim"),$i.checkArgument(typeof t=="string","Schema name must be string");var r=Kf[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var i=[],n=[];this._validateObject(e,r,"",i,n);var o={valid:i.length===0,errors:i,warnings:n,schema:t,claimHash:this.hash(e),canonical:this.canonicalize(e)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(a){return{success:!1,error:"Validation preparation failed: "+a.message}}},prepareClaimAttestation:function(e,t,r){try{$i.checkArgument(e&&typeof e=="object","Invalid claim"),$i.checkArgument(typeof t=="string","Schema name must be string"),$i.checkArgument(r&&typeof r=="object","Invalid attestor");var i=this.prepareClaimValidation(e,t);if(!i.success||!i.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:i};var n={type:"LTP_CLAIM_ATTESTATION",claimHash:i.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=K1.sha256(h.Buffer.from(this.canonicalize(n))).toString("hex");return n.attestationHash=o,{success:!0,attestation:n,claim:e,validation:i.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+i.validation.claimHash+"/attestations",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:i.validation.claimHash,attestorDid:n.attestor.did,attestationHash:o}}}}}catch(a){return{success:!1,error:"Attestation preparation failed: "+a.message}}},prepareClaimDispute:function(e,t,r){try{$i.checkArgument(typeof e=="string","Claim hash must be string"),$i.checkArgument(t&&typeof t=="object","Invalid disputant"),$i.checkArgument(r&&typeof r=="object","Invalid dispute");var i={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},n=K1.sha256(h.Buffer.from(this.canonicalize(i))).toString("hex");return i.disputeHash=n,{success:!0,dispute:i,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:i.disputant.did,disputeHash:n}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:n,priority:i.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{$i.checkArgument(Array.isArray(e),"Claims must be array"),$i.checkArgument(typeof t=="string","Schema name must be string");var r=[],i=[],n=0;e.forEach(function(s,u){try{var c=this.prepareClaimValidation(s,t);c.success&&c.validation.valid&&n++,r.push({index:u,result:c})}catch(l){i.push({index:u,error:l.message})}}.bind(this));var o=this._generateBatchId(),a=K1.sha256(h.Buffer.from(JSON.stringify(r.map(s=>s.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:a,totalClaims:e.length,validClaims:n,invalidClaims:e.length-n,validations:r,errors:i,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:a,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:n,invalid:e.length-n}}}}}}catch(s){return{success:!1,error:"Bulk validation preparation failed: "+s.message}}},canonicalize:function(e){$i.checkArgument(e&&typeof e=="object","Invalid claim");var t=this._sortObjectKeys(e);return JSON.stringify(t)},hash:function(e){var t=this.canonicalize(e);return K1.sha256(h.Buffer.from(t)).toString("hex")},prepareClaimTemplate:function(e,t){t=t||{};try{var r=Kf[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var i=this._createTemplateFromSchema(r),n=this._generateFormStructure(r);return{success:!0,schemaName:e,template:i,schema:r,formStructure:n,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:n,template:i}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:i,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return Kf},getSchemaNames:function(){return Object.keys(Kf)},getSchema:function(e){return Kf[e]||null},addSchema:function(e,t){$i.checkArgument(typeof e=="string","Schema name must be string"),$i.checkArgument(t&&typeof t=="object","Invalid schema"),Kf[e]=t},createTemplate:function(e){var t=Kf[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return K1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return Ese.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r],n={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(i),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(i)};i.enum&&(n.options=i.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(n)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.pattern&&(t[r]=i.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.enum&&(t[r]=i.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,i,n){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||i.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var a=this._getFieldPath(r,o),s=t.properties[o];s?this._validateValue(e[o],s,a,i,n):n.push("Unknown field: "+a)}.bind(this))):this._validateValue(e,t,r,i,n)},_validateValue:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&i.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateValue(e[a],t.items,r+"["+a+"]",i,n);t.type==="object"&&this._validateObject(e,t,r,i,n)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};dq.exports=Ose});var mq=k((vme,vq)=>{"use strict";v();var gq=Te(),V1=gq.crypto.Hash,Vl=gq.util.preconditions,Ise={prepareTokenCommitment:function(e,t){t=t||{},Vl.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,commitment:r,opReturnData:i,txTemplate:n,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},Vl.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,batchCommitment:r,opReturnData:i,txTemplate:n,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){Vl.checkArgument(e&&typeof e=="object","Invalid token"),Vl.checkArgument(typeof t=="string","Transaction ID must be string");try{var i=this._createCommitment(e,{}),n=this._extractOpReturn(r);if(!n)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(i,n);return{valid:o,chainVerified:!1,txid:t,commitment:i,anchorData:n,verifiedAt:new Date().toISOString()}}catch(a){return{valid:!1,error:a.message}}},formatRevocation:function(e,t){Vl.checkArgument(typeof e=="string","Token ID must be string"),Vl.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},i=V1.sha256(h.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:i,opReturnData:this._formatOpReturn({hash:i,type:"REVOCATION"},{})}}catch(n){return{success:!1,error:n.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),i={type:"LTP_TOKEN",tokenHash:V1.sha256(h.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},n=V1.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex");return{hash:n,data:i,canonical:r}},_createBatchCommitment:function(e,t){var r=[],i=[];e.forEach(function(s){var u=this._createCommitment(s,t);r.push(u.hash),i.push(s.id)}.bind(this));var n=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:n,tokenCount:e.length,tokenIds:i,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},a=V1.sha256(h.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:a,data:o,merkleRoot:n,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",i=e.hash;return{prefix:r,data:i,full:r+"."+i,bytes:h.Buffer.from(r+"."+i,"utf8"),size:h.Buffer.from(r+"."+i,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(i){throw new Error("Failed to create transaction template: "+i.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var i=r.script.replace("OP_RETURN ","");return{raw:i,decoded:h.Buffer.from(i,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=t[i+1]||n,a=h.Buffer.concat([h.Buffer.from(n,"hex"),h.Buffer.from(o,"hex")]),s=V1.sha256(a).toString("hex");r.push(s)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,i=148;return{base:t+r,withOneInput:t+r+i,bytesPerInput:i}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};vq.exports=Ise});var _q=k((yme,bq)=>{"use strict";v();var Gl=Te(),fo=Gl.crypto.Hash,yq=Gl.crypto.ECDSA,Ase=Gl.crypto.Signature,Pse=Gl.PrivateKey,Ii=Gl.util.preconditions,Tse={prepareSignatureProof:function(e,t,r){r=r||{},Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t instanceof Pse,"Invalid private key");try{var i=this._canonicalizeForSigning(e),n=fo.sha256(h.Buffer.from(i)),o=new yq;o.hashbuf=n,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var a=o.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(n,a),proofValue:a.toDER().toString("hex")};return{success:!0,proof:s,tokenHash:n.toString("hex"),canonical:i,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:n.toString("hex"),proof:s,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:n.toString("hex"),signature:a.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSignatureVerification:function(e,t){try{if(Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),i=fo.sha256(h.Buffer.from(r)),n=Ase.fromDER(h.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:i.toString("hex"),signature:n.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},a=new yq;a.hashbuf=i,a.sig=n,a.pubkey=Gl.PublicKey.fromString(t);var s=a.verify()===!0;return{success:!0,verification:{valid:s,tokenHash:i.toString("hex"),signatureValid:s,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:i.toString("hex"),result:s,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:s,verifier:t}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosure:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(Array.isArray(t),"Revealed fields must be array"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=this._createFieldCommitments(e,r),n=this._createMerkleTree(i),o=[],a=[];t.forEach(function(u){var c=this._getNestedValue(e,u),l=this._findFieldCommitment(i,u);if(l){o.push({path:u,value:c,commitment:l.hash,salt:l.salt});var m=this._generateMerkleProof(n,l.index);a.push({path:u,leafIndex:l.index,proof:m})}}.bind(this));var s={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:n.root,disclosures:o,merkleProofs:a,totalFields:i.length};return{success:!0,proof:s,hiddenFieldCount:i.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:s,merkleRoot:n.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:s,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:i.length,disclosedAt:new Date().toISOString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(Ii.checkArgument(e&&typeof e=="object","Invalid proof"),Ii.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],i=[];e.disclosures.forEach(function(o,a){var s=e.merkleProofs[a],u=this._hashField(o.path,o.value,o.salt);if(u!==o.commitment){i.push("Invalid commitment for field: "+o.path);return}var c=this._verifyMerkleProof(o.commitment,s.leafIndex,s.proof,e.merkleRoot);c?r.push({path:o.path,value:o.value,verified:!0}):i.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var n={valid:i.length===0,errors:i,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:n.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:i.length,result:n.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=t.requirements||[],n=[],o=!0;i.forEach(function(s){var u=this._checkLegalRequirement(e,s);n.push(u),u.satisfied||(o=!1)}.bind(this));var a={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:n,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:a,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:a,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:n}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:n.filter(s=>!s.satisfied)}}}}}catch(s){return{success:!1,error:s.message}}},prepareZeroKnowledgeProof:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t&&typeof t=="object","Invalid statement"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=fo.sha256(h.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),n={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:i,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:n,commitment:i,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:n,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:n,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var i={challenge:fo.sha256(h.Buffer.from(t.claim+r)).toString("hex"),response:fo.sha256(h.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:fo.sha256(h.Buffer.from(r+e.id+t.predicate)).toString("hex")};return i},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],i=0;return this._traverseObject(e,"",function(n,o){if(n!=="proof"&&n!=="tokenHash"){var a=fo.sha256(h.Buffer.from(t+n+i)).toString("hex"),s=this._hashField(n,o,a);r.push({path:n,value:o,salt:a,hash:s,index:i}),i++}}.bind(this)),r},_hashField:function(e,t,r){var i=e+":"+JSON.stringify(t)+":"+r;return fo.sha256(h.Buffer.from(i)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(l){return l.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],i=t;i.length>1;){for(var n=[],o=0;o<i.length;o+=2){var a=i[o],s=i[o+1]||a,u=h.Buffer.concat([h.Buffer.from(a,"hex"),h.Buffer.from(s,"hex")]),c=fo.sha256(u).toString("hex");n.push(c)}r.push(n),i=n}return{root:i[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],i=t,n=0;n<e.levels.length-1;n++){var o=e.levels[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r},_verifyMerkleProof:function(e,t,r,i){for(var n=e,o=t,a=0;a<r.length;a++){var s=r[a],u=o%2===0,c;s.isLeft?c=h.Buffer.concat([h.Buffer.from(s.hash,"hex"),h.Buffer.from(n,"hex")]):c=h.Buffer.concat([h.Buffer.from(n,"hex"),h.Buffer.from(s.hash,"hex")]),n=fo.sha256(c).toString("hex"),o=Math.floor(o/2)}return n===i},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(i,n){var o=t+"["+n+"]";this._traverseObject(i,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(i){var n=t?t+"."+i:i;this._traverseObject(e[i],n,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var i=new Date,n=new Date(e.issuanceDate);return{requirement:t.type,satisfied:n<=i};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var i={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return fo.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};bq.exports=Tse});var xq=k((Sme,Sq)=>{"use strict";v();var O5=Te(),G1=O5.crypto.Hash,_me=O5.Address,wme=O5.Transaction,Di=O5.util.preconditions,wq=z1(),kse={prepareRegistry:function(e){e=e||{},Di.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},Di.checkArgument(e&&typeof e=="object","Invalid token"),Di.checkArgument(t&&typeof t=="object","Invalid registry config");try{var i=this._validateTokenForRegistration(e,t);if(!i.valid)return{success:!1,error:"Token validation failed: "+i.error};var n={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:i.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:n.registeredAt,metadata:{status:n.status,tokenType:e.type,compliance:n.compliance}});return{success:!0,registrationRecord:n,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:i,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:n},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenApproval:function(e,t,r){try{Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(typeof t=="string","Approver must be string"),Di.checkArgument(r&&typeof r=="object","Invalid registry config");var i={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},n=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:i.approvedAt});return{success:!0,approvalData:i,auditEntry:n,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:n}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(t&&typeof t=="object","Invalid revocation"),Di.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var i={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},n={tokenId:e,status:"REVOKED",revokedAt:i.revokedAt,revocationReason:i.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:i.revokedAt,metadata:{reason:i.reason,legalBasis:i.legalBasis}});return{success:!0,revocationRecord:i,statusUpdate:n,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:i},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenStatusQuery:function(e,t){try{return Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{Di.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var i=e.offset||0,n=e.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(a){return{success:!1,error:a.message}}},prepareStatisticsQuery:function(e){return Di.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},Di.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var i=t.offset||0,n=t.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+wq.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,G1.sha256(h.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return G1.sha256(h.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],i=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),i=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),i=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),i=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),i=!1),{valid:i,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+wq.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)}};Sq.exports=kse});var Aq=k((Eme,Iq)=>{"use strict";v();var Vs=Te(),K7=Vs.crypto.Hash,Eq=Vs.crypto.ECDSA,Rse=Vs.crypto.Signature,Oq=Vs.PrivateKey,Xi=Vs.util.preconditions,Bse=z1();function Mse(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Vs.PublicKey?t.issuerPublicKey:Vs.PublicKey.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?Vs.PublicKey.fromString(i):null}catch{return null}}var I5={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},Zl={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},Li={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},A5={prepareObligationToken:function(e,t,r,i,n,o){o=o||{},Xi.checkArgument(typeof e=="string","Obligation type must be string"),Xi.checkArgument(typeof t=="string","Issuer DID must be string"),Xi.checkArgument(typeof r=="string","Obligor DID must be string"),Xi.checkArgument(i&&typeof i=="object","Obligation must be object"),Xi.checkArgument(n instanceof Oq,"Invalid issuer private key");var a=Object.values(I5);Xi.checkArgument(a.includes(e),"Invalid obligation type: "+e);try{var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:i,jurisdiction:o.jurisdiction||"US",priority:o.priority||Zl.MEDIUM,status:Li.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(s.credentialSubject.metadata=o.metadata);var u=this._signToken(s,n);return{success:!0,obligationToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:u,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,obligor:r,issuedAt:u.issuanceDate,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:u.id,issuer:t,obligor:r,obligationType:e,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},scheduleReminders:s.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:u.id,obligor:r,dueDate:s.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(c){return{success:!1,error:c.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateObligationType(e,r),this._validateObligationStatus(e,r,i),this._validateObligationPriority(e,i);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt,isOverdue:n.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:n.obligationType,issuer:n.issuerDID,obligor:n.obligorDID,result:n.valid,verifiedAt:n.verifiedAt}},updateStatus:n.isOverdue&&e.credentialSubject.status===Li.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:Li.OVERDUE,updatedAt:n.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,i){i=i||{},Xi.checkArgument(e&&typeof e=="object","Invalid token"),Xi.checkArgument(t&&typeof t=="object","Invalid fulfillment"),Xi.checkArgument(r instanceof Oq,"Invalid obligor key");try{var n=this.prepareObligationVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+n.verification.errors.join(", ")};if(e.credentialSubject.status===Li.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===Li.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},a=this._signToken(o,r),s=o.credentialSubject.completionPercentage>=100?Li.COMPLETED:Li.IN_PROGRESS;return{success:!0,fulfillmentRecord:a,newStatus:s,fulfillmentId:a.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:a,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:s,fulfillmentId:a.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:s}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(u){return{success:!1,error:u.message}}},prepareObligationBreachAssessment:function(e,t,r){Xi.checkArgument(e&&typeof e=="object","Invalid token"),Xi.checkArgument(t&&typeof t=="object","Invalid breach details"),Xi.checkArgument(r&&typeof r=="object","Invalid assessor");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},n=K7.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex");return i.credentialSubject.assessmentHash=n,{success:!0,breachAssessment:i,breachId:i.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:i,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:Li.BREACHED,breachId:i.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:i.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,assessedAt:i.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},Xi.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},i=new Date,n=new Date(i.getTime()+10080*60*1e3);return e.forEach(function(o){var a={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var s=new Date(o.credentialSubject.dueDate);a.isDueSoon=s<=n&&s>i}r.summary.byStatus[a.status]=(r.summary.byStatus[a.status]||0)+1,r.summary.byPriority[a.priority]=(r.summary.byPriority[a.priority]||0)+1,r.summary.byType[a.type]=(r.summary.byType[a.type]||0)+1,a.isOverdue&&r.summary.overdue++,a.isDueSoon&&r.summary.dueSoon++,a.status===Li.COMPLETED&&r.summary.completed++,a.isOverdue&&a.priority===Zl.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),a.isDueSoon&&a.priority===Zl.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(a)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return I5},getObligationPriority:function(){return Zl},getObligationStatus:function(){return Li},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=K7.sha256(h.Buffer.from(r)),n=new Eq;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=K7.sha256(h.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=Mse(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=Rse.fromDER(h.Buffer.from(a[2],"base64url")),u=new Eq;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);i<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var a=new Date(e.credentialSubject.expirationDate);i>a&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(I5);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var i=Object.values(Li);i.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===Li.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(Zl);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==Li.COMPLETED},_generateUUID:function(){return Bse.uuid4()}};A5.ObligationTypes=I5;A5.ObligationPriority=Zl;A5.ObligationStatus=Li;Iq.exports=A5});var kq=k((Ime,Tq)=>{"use strict";v();var Vf=lq(),P5=pq(),Z1=mq(),V7=_q(),na=xq(),Nse=Aq(),Pq=Te(),G7=Pq.PrivateKey,Ji=Pq.util.preconditions,wt=function(e){return this instanceof wt?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=na.createRegistry(this.config.registry)),this):new wt(e)};wt.prototype.createRightToken=function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid right data"),Ji.checkArgument(t instanceof G7,"Invalid private key"),r=r||{};try{var i=Vf.create(e.type,e.owner,e.owner,e,t,r);if(!i)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(i=Vf._signToken(i,t)),r.anchor){var n=Z1.anchorToken(i,r.anchor);n.success&&(i.anchorTx=n.txid,i.anchorBlock=n.blockHeight)}if(this.registry&&r.register!==!1){var o=na.registerToken(this.registry,i,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(i.registrationId=o.registrationId,i.registrationStatus=o.status)}return{success:!0,token:i,type:"LegalRightToken"}}catch(a){return{success:!1,error:a.message}}};wt.prototype.validateClaim=function(e,t){return P5.validate(e,t)};wt.prototype.createSelectiveDisclosure=function(e,t,r){return V7.prepareSelectiveDisclosure(e,t,r)};wt.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:Vf.verifyToken(e,t)};wt.prototype.transferRight=function(e,t,r,i){Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(typeof t=="string","New owner must be string"),Ji.checkArgument(r instanceof G7,"Invalid owner key"),i=i||{};try{var n=this.verifyToken(e,r.toPublicKey().toString());if(!n.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=Vf.prepareRightTokenTransfer(e,t,r,i);if(!o.success)return{success:!1,error:o.error};var a=o.newToken,s=o.transferProof;if(i.anchor){var u=Z1.anchorToken(a,i.anchor);u.success&&(a.transferAnchorTx=u.txid)}if(this.registry){var c=na.registerToken(this.registry,a,{registeredBy:i.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});c.success&&(a.registrationId=c.registrationId)}return{success:!0,token:a,transferId:s.id,transferredAt:s.issuanceDate,transferProof:s}}catch(l){return{success:!1,error:l.message}}};wt.prototype.createObligation=function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid right token"),Ji.checkArgument(t&&typeof t=="object","Invalid obligation data"),Ji.checkArgument(r instanceof G7,"Invalid private key");try{var i=Vf.prepareObligationToken(e,t.obligor,t,r);return i.success?{success:!0,obligation:i.obligationToken,rightTokenId:e.id}:{success:!1,error:i.error}}catch(n){return{success:!1,error:n.message}}};wt.prototype.revokeToken=function(e,t,r){return Ji.checkArgument(typeof e=="string","Token ID must be string"),Ji.checkArgument(t&&typeof t=="object","Invalid revocation data"),Ji.checkArgument(typeof r=="string","Authority must be string"),this.registry?na.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};wt.prototype.checkTokenStatus=function(e){return Ji.checkArgument(typeof e=="string","Token ID must be string"),this.registry?na.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};wt.prototype.searchTokens=function(e){return this.registry?na.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};wt.prototype.getRegistryStats=function(){return this.registry?na.getStatistics(this.registry):{error:"No registry available"}};wt.prototype.createLegalValidityProof=function(e,t,r){return V7.prepareLegalValidityProof(e,t,r)};wt.prototype.anchorTokenBatch=function(e,t){return Z1.anchorBatch(e,t)};wt.prototype.verifyAnchor=function(e,t){return Z1.verifyAnchor(e,t)};wt.prototype.getRightTypes=function(){return Vf.getRightTypes()};wt.prototype.getClaimSchemas=function(){return P5.getSchemas()};wt.prototype.createRegistry=function(e){return this.registry=na.createRegistry(e),this.registry};wt.prototype.setRegistry=function(e){Ji.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};wt.create=function(e){return new wt(e)};wt.createRightToken=function(e,t,r){var i=new wt;return i.createRightToken(e,t,r)};wt.validateClaim=function(e,t){return P5.validate(e,t)};wt.verifyToken=function(e,t){var r=new wt;return r.verifyToken(e,t)};wt.createRegistry=function(e){return na.createRegistry(e)};wt.Right=Vf;wt.Claim=P5;wt.Anchor=Z1;wt.Proof=V7;wt.Registry=na;wt.Obligation=Nse;Tq.exports=wt});var Te=k((Pme,Rq)=>{"use strict";v();var j=Rq.exports;j.deps=j.deps||{};j.deps._=xt();j.deps.Buffer=typeof h.Buffer<"u"?h.Buffer:null;if(typeof window>"u")j.deps.bnjs=Nn(),j.deps.bs58=Y2();else{try{j.deps.bnjs=Nn()}catch{}try{j.deps.bs58=Y2()}catch{}}j.version="v"+Km();j.versionGuard=function(e){if(e!==void 0){var t=`
97
+ `);let i=new Lr.Script.Interpreter,n=new Lr.crypto.BN(1e5),o=i.verify(e,t,r,0,Lr.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(a=>a.toString("hex"))),console.log("AltStack:",i.altstack.map(a=>a.toString("hex"))),console.log("===========================================")}async function qN(){if(typeof A.default>"u"||!A.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=A.default.argv.slice(2),t=w=>{let E=e.indexOf(w);return E!==-1&&e[E+1]?e[E+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),a=e.includes("--truth"),s,u,c;if(n)c=q6(n);else{s=q6(r),u=q6(i);let w=h.Buffer.concat([s.toBuffer(),u.toBuffer()]);c=Lr.Script.fromBuffer(w)}let l=new Lr.Transaction,m=new Lr.Transaction.Input({prevTxId:"0".repeat(64),outputIndex:0,script:Lr.Script.empty(),satoshis:1e5,output:new Lr.Transaction.Output({satoshis:1e5,script:Lr.Script.empty()})});l.addInput(m),l.addOutput(new Lr.Transaction.Output({satoshis:1e5,script:Lr.Script.empty()})),o?await DN(c,l,!0):a?LN(s||Lr.Script.empty(),u||Lr.Script.empty(),l):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}B8.exports={parseScript:q6,printStack:R8,stepThroughScript:DN,runFullEvaluation:LN,main:qN};typeof Fr<"u"&&Fr.main===B8&&qN()});var Go=k(($ge,zN)=>{"use strict";v();var vi=Te(),F6=fr(),lne=cr(),FN=Vr(),M8=FN.SIGHASH_ALL|FN.SIGHASH_FORKID;function HN(){var e=vi.Script.Interpreter;return e.SCRIPT_VERIFY_P2SH|e.SCRIPT_VERIFY_STRICTENC|e.SCRIPT_VERIFY_DERSIG|e.SCRIPT_VERIFY_LOW_S|e.SCRIPT_VERIFY_MINIMALDATA|e.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY|e.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY|e.SCRIPT_ENABLE_SIGHASH_FORKID|e.SCRIPT_ENABLE_MAGNETIC_OPCODES|e.SCRIPT_ENABLE_MONOLITH_OPCODES}function hne(e){return vi.Script.Interpreter.useGenesisLimits(e)}function dne(e,t,r){r=r||{};var i=new vi.Script.Interpreter,n=i.verify(e,t,r.tx||new vi.Transaction,r.inputIndex||0,r.flags||HN(),new F6(r.satoshis||0));return{ok:n,err:i.errstr||""}}function jN(e,t,r,i,n){return vi.Transaction.sighash.sighashPreimage(e,n||M8,t,r,new F6(i))}function pne(e,t,r,i,n){return lne.sha256sha256(jN(e,t,r,i,n))}function gne(e,t,r,i,n,o){o=o||M8;var a=vi.Transaction.sighash.sign(e,t,o,r,i,new F6(n));return h.Buffer.concat([a.toDER(),h.Buffer.from([o])])}function vne(e,t,r){r=r||{};var i=new vi.Transaction().addOutput(new vi.Transaction.Output({script:e,satoshis:t})),n=new vi.Transaction;return n.addInput(new vi.Transaction.Input({prevTxId:i.hash,outputIndex:0,script:vi.Script.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function mne(e,t){var r=e.toAddress?e.toAddress():e;return new vi.Transaction.Output({script:vi.Script.buildPublicKeyHashOut(r),satoshis:t})}function yne(e){return e===0?vi.Opcode.OP_0:e===-1?vi.Opcode.OP_1NEGATE:e>=1&&e<=16?vi.Opcode["OP_"+e]:new F6(e).toScriptNumBuffer()}zN.exports={SIGHASH:M8,flags:HN,enableGenesis:hne,verify:dne,rawPreimage:jN,sighashDigest:pne,signInput:gne,fundAndSpend:vne,p2pkhOutput:mne,scriptNum:yne}});var YN=k((Jge,WN)=>{"use strict";v();var KN=Te(),VN=cr(),GN=Go(),ao=KN.Script,Ar=KN.Opcode,b1=GN.signInput,ZN=GN.scriptNum;function bne(e){var t=VN.sha256(e),r=new ao().add(Ar.OP_SHA256).add(t).add(Ar.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new ao().add(o||e)}}}function _ne(e){var t=e.toPublicKey(),r=ao.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new ao().add(b1(i,e,0,r,n)).add(t.toBuffer())}}}function wne(e,t){var r=e.toPublicKey(),i=new ao().add(ZN(t)).add(Ar.OP_CHECKLOCKTIMEVERIFY).add(Ar.OP_DROP).add(r.toBuffer()).add(Ar.OP_CHECKSIG);return{lock:i,meta:{name:"cltv-timelock",locktime:t},unlock:function(n,o){return new ao().add(b1(n,e,0,i,o))}}}function Sne(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new ao().add(Ar["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ar["OP_"+r.length]).add(Ar.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,a){a=a||t.slice(0,e);var s=new ao().add(Ar.OP_0);return a.forEach(function(u){s.add(b1(n,u,0,i,o))}),s}}}function xne(e){var t=VN.sha256(e.secret),r=new ao().add(Ar.OP_IF).add(Ar.OP_SHA256).add(t).add(Ar.OP_EQUALVERIFY).add(e.receiver.toPublicKey().toBuffer()).add(Ar.OP_CHECKSIG).add(Ar.OP_ELSE).add(ZN(e.timeout)).add(Ar.OP_CHECKLOCKTIMEVERIFY).add(Ar.OP_DROP).add(e.sender.toPublicKey().toBuffer()).add(Ar.OP_CHECKSIG).add(Ar.OP_ENDIF);return{lock:r,meta:{name:"htlc",digest:t.toString("hex"),timeout:e.timeout},unlockClaim:function(i,n){return new ao().add(b1(i,e.receiver,0,r,n)).add(e.secret).add(Ar.OP_1)},unlockRefund:function(i,n){return new ao().add(b1(i,e.sender,0,r,n)).add(Ar.OP_0)}}}WN.exports={hashLock:bne,p2pkh:_ne,timeLockCLTV:wne,multisig:Sne,htlc:xne}});var Tl=k((eve,iC)=>{"use strict";v();var C8=Te(),H6=fr(),$N=cr(),D8=Go(),XN=C8.Script,Nt=C8.Opcode,L8=D8.SIGHASH,j6=D8.scriptNum,Pl=h.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),q8=new H6("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Ene=h.Buffer.concat([h.Buffer.from([2]),Pl]),JN=h.Buffer.from(Pl).reverse(),QN=h.Buffer.concat([h.Buffer.from(q8.toBuffer()).reverse(),h.Buffer.from([0])]),One=h.Buffer.concat([h.Buffer.from([48,68,2,32]),Pl,h.Buffer.from([2,32])]);function N8(e,t){var r;for(r=0;r<t-1;r++)e.add(Nt.OP_1).add(Nt.OP_SPLIT);for(r=0;r<t-1;r++)e.add(Nt.OP_SWAP).add(Nt.OP_CAT);return e}var Zo=C8.crypto.Signature,Ine=Zo.SIGHASH_ALL|Zo.SIGHASH_FORKID,Ane=Zo.SIGHASH_SINGLE|Zo.SIGHASH_FORKID,Pne=Zo.SIGHASH_SINGLE|Zo.SIGHASH_ANYONECANPAY|Zo.SIGHASH_FORKID,Tne=Zo.SIGHASH_ALL|Zo.SIGHASH_ANYONECANPAY|Zo.SIGHASH_FORKID;function U8(e,t){var r=t&&t.sighashType||L8;return e.add(Nt.OP_HASH256),N8(e,32),e.add(JN).add(Nt.OP_ADD),e.add(QN).add(Nt.OP_MOD),e.add(j6(32)).add(Nt.OP_NUM2BIN),N8(e,32),e.add(Pl).add(Nt.OP_DUP),e.add(Nt.OP_2).add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(Nt.OP_TOALTSTACK),e.add(h.Buffer.from([48,68,2,32])).add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(h.Buffer.from([2,32])).add(Nt.OP_CAT),e.add(Nt.OP_SWAP).add(Nt.OP_CAT),e.add(h.Buffer.from([r])).add(Nt.OP_CAT),e.add(Nt.OP_FROMALTSTACK).add(Nt.OP_CHECKSIG),e}function kne(){return U8(new XN)}function eC(e){return e.add(j6(40)).add(Nt.OP_RIGHT).add(j6(32)).add(Nt.OP_LEFT),e}function Rne(e){return tC(e,L8)}function tC(e,t){var r=h.Buffer.from([t&255,0,0,0]);return e.add(Nt.OP_DUP).add(j6(4)).add(Nt.OP_RIGHT).add(r).add(Nt.OP_EQUALVERIFY),e}function Bne(e){var t=h.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return $N.sha256sha256(t)}function Mne(e){var t=new XN().add(Nt.OP_DUP);return U8(t),t.add(Nt.OP_VERIFY),eC(t),t.add(h.Buffer.from(e)).add(Nt.OP_EQUAL),t}var Nne=new H6("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function rC(e){var t=$N.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new H6(t).add(new H6(Pl)).mod(q8);if(r.gt(Nne))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function Cne(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,a=n.start||0,s=n.field||"nLockTime",u=n.sighashType||L8;if(s!=="nLockTime"&&s!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var c=e.inputs[t],l=0;l<o;l++){var m=a+l;s==="nLockTime"?e.nLockTime=m:c.sequenceNumber=4294967294-m;var w=D8.rawPreimage(e,t,r,i,u);if(rC(w))return{preimage:w,tries:l+1,field:s,nonce:m}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}iC.exports={Gx:Pl,N:q8,PUBKEY:Ene,gxLe:JN,N_LE:QN,DER_PREFIX:One,reverseBytes:N8,pushTxCore:U8,authenticator:kne,extractHashOutputs:eC,assertSighashAll:Rne,assertSighashType:tC,SIGHASH_ALL_FORKID:Ine,SIGHASH_SINGLE_FORKID:Ane,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Pne,SIGHASH_ALL_ANYONECANPAY_FORKID:Tne,hashOutputs:Bne,valueCovenant:Mne,sFromPreimage:rC,grind:Cne}});var H8=k((rve,oC)=>{"use strict";v();var nC=Te(),F8=Tl(),Dne=Go(),Lne=nC.Script,Pr=nC.Opcode,kl=Dne.scriptNum;function qne(e){var t=new Lne;return t.add(Pr.OP_DUP),F8.pushTxCore(t),t.add(Pr.OP_VERIFY),F8.assertSighashAll(t),t.add(Pr.OP_DUP),t.add(kl(104)).add(Pr.OP_SPLIT).add(Pr.OP_NIP),t.add(Pr.OP_SIZE).add(kl(52)).add(Pr.OP_SUB).add(Pr.OP_SPLIT).add(Pr.OP_DROP),t.add(Pr.OP_OVER),t.add(kl(52)).add(Pr.OP_RIGHT).add(kl(8)).add(Pr.OP_LEFT),t.add(Pr.OP_BIN2NUM).add(kl(e)).add(Pr.OP_SUB),t.add(kl(8)).add(Pr.OP_NUM2BIN),t.add(Pr.OP_SWAP).add(Pr.OP_CAT),t.add(Pr.OP_HASH256),t.add(Pr.OP_SWAP),F8.extractHashOutputs(t),t.add(Pr.OP_EQUAL),t}oC.exports={pelsCovenant:qne}});var K8=k((nve,sC)=>{"use strict";v();var K6=Te(),aC=cr(),z8=Go(),$t=K6.Opcode,Rl=z8.scriptNum;function z6(e){return e instanceof K6.PrivateKey?e.toPublicKey().toBuffer():e instanceof K6.PublicKey?e.toBuffer():e}function Une(){return{name:"single-key",commit:function(e){return aC.sha256ripemd160(z6(e))},emit:function(e){return e.add($t.OP_OVER).add($t.OP_HASH160).add($t.OP_EQUALVERIFY),e.add($t.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=z8.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function j8(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new K6.Script().add($t["OP_"+e]);return t.forEach(function(n){i.add(h.Buffer.from(n))}),i.add($t["OP_"+r]).add($t.OP_CHECKMULTISIG),i.toBuffer()}function Fne(e,t){if(typeof t!="number"||!Number.isInteger(t))throw new Error("multisig(m, nKeys): nKeys is the NUMBER of keys, not the keys themselves"+(Array.isArray(t)?" \u2014 pass "+t.length+" instead of the array":""));if(typeof e!="number"||!Number.isInteger(e))throw new Error("multisig(m, nKeys): m must be an integer");if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return aC.sha256ripemd160(j8(e,r.map(z6)))},emit:function(r){r.add($t.OP_OVER).add($t.OP_HASH160).add($t.OP_EQUALVERIFY),r.add(Rl(1)).add($t.OP_SPLIT).add($t.OP_NIP),r.add($t.OP_SIZE).add(Rl(2)).add($t.OP_SUB).add($t.OP_SPLIT).add($t.OP_DROP);for(var i=0;i<this.n;i++)r.add(Rl(34)).add($t.OP_SPLIT),r.add($t.OP_SWAP).add(Rl(1)).add($t.OP_SPLIT).add($t.OP_NIP),r.add($t.OP_TOALTSTACK);for(r.add($t.OP_DROP),r.add(Rl(this.m)),i=0;i<this.n;i++)r.add($t.OP_FROMALTSTACK);return r.add(Rl(this.n)),r.add($t.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,a){var s=a.keys;if(s.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var u=j8(e,s.map(z6)),c=s.map(z6).map(function(w){return w.toString("hex")}),l=a.signWith.map(function(w){var E=c.indexOf(w.toPublicKey().toBuffer().toString("hex"));if(E<0)throw new Error("signWith key is not in the committed key set");return{idx:E,priv:w}}).sort(function(w,E){return E.idx-w.idx}).slice(0,e);if(l.length<e)throw new Error("need at least "+e+" signing keys");var m=l.map(function(w){return z8.signInput(r,w.priv,i,n,o)});return[$t.OP_0].concat(m).concat([u])}}}function Hne(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}sC.exports={singleKey:Une,multisig:Fne,predicate:Hne,redeemScript:j8}});var Z8=k((ave,gC)=>{"use strict";v();var V8=Te(),_1=Tl(),G8=Go(),w1=K8(),V6=V8.Script,Ie=V8.Opcode,Wo=G8.scriptNum;function fC(e,t){var r=h.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function uC(e,t){return t.length?e.add(h.Buffer.from(t)):e.add(Ie.OP_0)}function cC(e,t){return e.add(Ie.OP_DUP),_1.pushTxCore(e),e.add(Ie.OP_VERIFY),_1.assertSighashAll(e),e.add(Ie.OP_DUP).add(Wo(52)).add(Ie.OP_RIGHT).add(Wo(8)).add(Ie.OP_LEFT).add(Ie.OP_TOALTSTACK),e.add(Ie.OP_DUP),_1.extractHashOutputs(e),e.add(Ie.OP_TOALTSTACK),e.add(Wo(104)).add(Ie.OP_SPLIT).add(Ie.OP_NIP).add(Ie.OP_SIZE).add(Wo(52)).add(Ie.OP_SUB).add(Ie.OP_SPLIT).add(Ie.OP_DROP),e.add(Ie.OP_DUP).add(Wo(4)).add(Wo(20)).add(Ie.OP_SUBSTR),e.add(Ie.OP_SWAP).add(Ie.OP_TOALTSTACK),t.emit(e),e.add(Ie.OP_FROMALTSTACK),e}function lC(e){return e.add(Wo(4)).add(Ie.OP_SPLIT).add(Wo(20)).add(Ie.OP_SPLIT).add(Ie.OP_NIP),e.add(Ie.OP_TOALTSTACK),e.add(Ie.OP_SWAP).add(Ie.OP_CAT),e.add(Ie.OP_FROMALTSTACK).add(Ie.OP_CAT),e}function hC(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function jne(e,t,r){r=r||w1.singleKey();var i=new V6;return i.add(fC(t,r)),i.add(Ie.OP_DROP),cC(i,r),lC(i),i.add(Ie.OP_FROMALTSTACK),i.add(Ie.OP_SWAP),i.add(Ie.OP_FROMALTSTACK),i.add(Ie.OP_BIN2NUM).add(Wo(e)).add(Ie.OP_SUB).add(Wo(8)).add(Ie.OP_NUM2BIN),i.add(Ie.OP_SWAP).add(Ie.OP_CAT),i.add(Ie.OP_HASH256),i.add(Ie.OP_EQUAL),hC(i)}function dC(e,t){t=t||w1.singleKey();var r=new V6;return r.add(fC(e,t)),r.add(Ie.OP_DROP),cC(r,t),lC(r),r.add(Ie.OP_CAT),r.add(Ie.OP_SWAP).add(Ie.OP_CAT),r.add(Ie.OP_CAT),r.add(Ie.OP_FROMALTSTACK),r.add(Ie.OP_FROMALTSTACK).add(Ie.OP_DROP),r.add(Ie.OP_SWAP).add(Ie.OP_HASH256).add(Ie.OP_EQUAL),hC(r)}function zne(e){return w1.singleKey().commit(e)}function Kne(e,t,r,i,n,o){o=o||{};var a=o.auth||w1.singleKey(),s=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");_1.grind(r,s,n,i,o.grind);var u=G8.rawPreimage(r,s,n,i),c=a.unlockArgs(r,s,n,i,e),l=new V6().add(h.Buffer.from(t));return c.forEach(function(m){l.add(m)}),l.add(h.Buffer.from(u)),l}function pC(e,t,r,i,n,o,a){a=a||{};var s=a.auth||w1.singleKey(),u=a.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");_1.grind(r,u,n,i,a.grind);var c=G8.rawPreimage(r,u,n,i),l=s.unlockArgs(r,u,n,i,e),m=new V6;return uC(m,o.before||h.Buffer.alloc(0)),uC(m,o.after||h.Buffer.alloc(0)),m.add(h.Buffer.from(o.tokenValue)),m.add(h.Buffer.from(t)),l.forEach(function(w){m.add(w)}),m.add(h.Buffer.from(c)),m}function Vne(e,t){return dC(e,t)}function Gne(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var a=o.tokenIndex||0,s=r.outputs||[],u=s[a];if(!u)throw new Error("transferOrdinal: spend has no output at tokenIndex "+a);if(u.satoshis!==i)throw new Error("transferOrdinal: token output value ("+u.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function c(E){return E.toBufferWriter().toBuffer()}var l=h.Buffer.concat(s.slice(0,a).map(c)),m=h.Buffer.concat(s.slice(a+1).map(c)),w=new V8.crypto.BN(i).toBuffer({endian:"little",size:8});return pC(e,t,r,i,n,{before:l,after:m,tokenValue:w},o)}gC.exports={ownershipToken:jne,ownershipTokenMulti:dC,ordinalLock:Vne,ownerId:zne,unlockTransfer:Kne,unlockTransferMulti:pC,transferOrdinal:Gne}});var e7=k((uve,vC)=>{"use strict";v();var X8=Te(),G6=Tl(),Zne=H8(),Wne=Z8(),J8=Go(),Y8=X8.Script,xn=X8.Opcode,$8=X8.Transaction,W8=J8.scriptNum;function Yne(e,t){return e instanceof $8.Output?e:e instanceof Y8?new $8.Output({script:e,satoshis:t}):J8.p2pkhOutput(e,t)}function $ne(e,t,r,i,n,o){o=o||5e4;for(var a=0;a<o;a++){e.nLockTime=n+a;var s=J8.rawPreimage(e,t,r,i);if(G6.sFromPreimage(s))return s}throw new Error("covenant grind failed after "+o+" tries")}function $a(){if(!(this instanceof $a))return new $a;this._outputs=[],this._minLockTime=null}$a.prototype.payTo=function(e,t){return this._outputs.push(Yne(e,t)),this};$a.prototype.lockUntil=function(e){return this._minLockTime=e,this};$a.prototype.outputs=function(){return this._outputs.map(function(e){return new $8.Output(e.toObject())})};$a.prototype.describe=function(){var e=[];return this._outputs.forEach(function(t,r){e.push("output["+r+"] = "+t.satoshis+" sat to "+t.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null&&e.push("nLockTime >= "+this._minLockTime),"spend allowed iff: "+e.join(" AND ")};$a.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new Y8().add(xn.OP_DUP);if(G6.pushTxCore(t),t.add(xn.OP_VERIFY),this._outputs.length){var r=G6.hashOutputs(this._outputs);t.add(xn.OP_DUP),G6.extractHashOutputs(t),t.add(h.Buffer.from(r)).add(xn.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add(xn.OP_DUP),t.add(W8(8)).add(xn.OP_RIGHT).add(W8(4)).add(xn.OP_LEFT),t.add(xn.OP_BIN2NUM).add(W8(this._minLockTime)).add(xn.OP_GREATERTHANOREQUAL).add(xn.OP_VERIFY)),t.add(xn.OP_DROP).add(xn.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var a=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new Y8().add($ne(i,o,t,n,a))}}};function Q8(){return new $a}Q8.perpetual=function(e){return Zne.pelsCovenant(e)};Q8.token=function(e,t){return Wne.ownershipToken(e,t)};vC.exports={policy:Q8,Policy:$a}});var wC=k((cve,_C)=>{"use strict";v();var Z6=Te(),Xne=Go();function yC(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return Z6.Opcode.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function mC(e,t){t=t||16;var r=h.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function Jne(e,t,r){r=r||{};var i=new Z6.Script.Interpreter,n=[];i.stepListener=function(a,s,u){n.push({phase:i.script===t?"lock":"unlock",op:yC(a.opcode&&typeof a.opcode.toNumber=="function"?a.opcode.toNumber():a.opcode.num),stack:s.map(function(c){return mC(c)}),altstack:u.map(function(c){return mC(c)})})};var o=i.verify(e,t,r.tx||new Z6.Transaction,r.inputIndex||0,typeof r.flags=="number"?r.flags:Xne.flags(),new Z6.crypto.BN(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function bC(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",a=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+a)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
98
+ `)}function Qne(e){return console.log(bC(e)),e}_C.exports={trace:Jne,format:bC,print:Qne,opLabel:yC}});var xC=k((hve,SC)=>{"use strict";v();var S1=Te(),ie={Covenant:cN(),Preimage:Vo(),SIGHASH:dN(),Builder:gN(),UTXOGenerator:EN(),ScriptTester:IN(),CovenantBuilder:I8().CovenantBuilder,CovenantTemplates:I8().CovenantTemplates,OpcodeMap:x8(),ScriptUtils:MN(),StackExaminer:CN(),ScriptInterpreter:UN(),CovenantHelpers:Go(),Locks:YN(),PushTx:Tl(),PELS:H8(),Token:Z8(),Authorizers:K8(),DSL:e7(),Policy:e7().Policy,Debugger:wC()};ie.policy=ie.DSL.policy;ie.trace=function(e,t,r){return ie.Debugger.trace(e,t,r)};ie.enableGenesis=function(e){return ie.CovenantHelpers.enableGenesis(e)};ie.verifyScript=function(e,t,r){return ie.CovenantHelpers.verify(e,t,r)};ie.perpetualCovenant=function(e){return ie.PELS.pelsCovenant(e)};ie.ownershipToken=function(e,t,r){return ie.Token.ownershipToken(e,t,r)};ie.valueCovenant=function(e){return ie.PushTx.valueCovenant(e)};ie.ordinalLock=function(e,t){return ie.Token.ordinalLock(e,t)};ie.transferOrdinal=function(e,t,r,i,n,o){return ie.Token.transferOrdinal(e,t,r,i,n,o)};ie.createCovenant=function(e,t){return new ie.Covenant(e,t)};ie.extractPreimage=function(e,t){return new ie.Preimage(e,t)};ie.analyzeSIGHASH=function(e){return new ie.SIGHASH(e)};ie.buildCovenant=function(e,t){return new ie.Builder(e,t)};ie.createUTXOGenerator=function(e){return new ie.UTXOGenerator(e)};ie.createTestEnvironment=function(e){return ie.UTXOGenerator.createTestEnvironment(e)};ie.testScript=function(e,t,r){return ie.ScriptTester.test(e,t,r)};ie.testCovenant=function(e,t,r){return ie.ScriptTester.testCovenant(e,t,r)};ie.testFieldExtraction=function(e,t,r){return ie.ScriptTester.testFieldExtraction(e,t,r)};ie.debugScript=function(e,t){var r=new ie.ScriptTester(t);return r.debug(e)};ie.explainZeroHashes=function(){return ie.SIGHASH.explainZeroMystery()};ie.getAllSIGHASHTypes=function(){return ie.SIGHASH.getAllTypes()};ie.demonstrateAllSIGHASH=function(){return ie.SIGHASH.generateAllDemonstrations()};ie.createCovenantBuilder=function(){return new ie.CovenantBuilder};ie.createValueLockCovenant=function(e){return ie.CovenantTemplates.valueLock(e)};ie.createHashLockCovenant=function(e){return ie.CovenantTemplates.hashLock(e)};ie.createComplexValidationCovenant=function(e){return ie.CovenantTemplates.complexValidation(e)};ie.getOpcodeMap=function(){return ie.OpcodeMap.opcodeMap};ie.simulateScript=function(e,t){return ie.OpcodeMap.utils.simulate(e,t)};ie.createASMFromJS=function(e){return ie.OpcodeMap.utils.createASM(e)};ie.scriptToASM=function(e){return ie.ScriptUtils.scriptToASM(e)};ie.asmToScript=function(e){return ie.ScriptUtils.asmToScript(e)};ie.asmToHex=function(e){return ie.ScriptUtils.asmToHex(e)};ie.hexToASM=function(e){return ie.ScriptUtils.hexToASM(e)};ie.scriptToHex=function(e){return ie.ScriptUtils.scriptToHex(e)};ie.validateASM=function(e){return ie.ScriptUtils.validateASM(e)};ie.validateScript=function(e){return ie.ScriptUtils.validateScript(e)};ie.estimateScriptSize=function(e){return ie.ScriptUtils.estimateScriptSize(e)};ie.optimizeScript=function(e){return ie.ScriptUtils.optimizeScript(e)};ie.compareScripts=function(e,t){return ie.ScriptUtils.compareScripts(e,t)};ie.explainScript=function(e){return ie.ScriptUtils.explainScript(e)};ie.scriptMetrics=function(e){return ie.ScriptUtils.scriptMetrics(e)};ie.analyzeComplexity=function(e){return ie.ScriptUtils.analyzeComplexity(e)};ie.findOptimizations=function(e){return ie.ScriptUtils.findOptimizations(e)};ie.covenantToEnglish=function(e){return ie.ScriptUtils.covenantToEnglish(e)};ie.batchTestScripts=function(e,t){return ie.ScriptUtils.batchTestScripts(e,t)};ie.examineStack=function(e,t){return ie.StackExaminer.runScript(e,t)};ie.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?ie.ScriptInterpreter.stepThroughScript(ie.ScriptInterpreter.parseScript(e+" "+t),new S1.Transaction,!0):ie.ScriptInterpreter.runFullEvaluation(ie.ScriptInterpreter.parseScript(e),ie.ScriptInterpreter.parseScript(t),new S1.Transaction)};ie.parseScript=function(e){return ie.ScriptInterpreter.parseScript(e)};ie.printStack=function(e,t){return ie.ScriptInterpreter.printStack(e,t)};ie.createQuickCovenant=function(e,t){let r=ie.createCovenantBuilder();switch(e){case"value_lock":return r.comment(`Value lock: minimum ${t.value} satoshis`).extractField("value").push(t.value).greaterThanOrEqual().verify().build();case"hash_lock":return r.comment(`Hash lock: requires preimage of ${t.hash}`).push("secret_placeholder").sha256().push(t.hash).equalVerify().build();case"time_lock":return r.comment(`Time lock: requires nLockTime > ${t.timestamp}`).extractField("nLockTime").push(t.timestamp).greaterThan().verify().build();case"multi_condition":let i=r.comment("Multi-condition covenant");return t.conditions.forEach(n=>{switch(n.type){case"value":i=i.extractField("value").push(n.value).greaterThanOrEqual().verify();break;case"hash":i=i.push("secret_placeholder").sha256().push(n.hash).equalVerify();break;case"time":i=i.extractField("nLockTime").push(n.timestamp).greaterThan().verify();break}}),i.build();default:throw new Error(`Unknown covenant type: ${e}`)}};ie.completeCovenantFlow=function(e,t,r){var i=new ie.Covenant(e);return i.completeFlow(t,r)};ie.getEducationalResources=function(){return{zeroHashMystery:ie.SIGHASH.explainZeroMystery(),sighashTypes:ie.SIGHASH.getAllTypes(),exampleDemonstrations:ie.SIGHASH.generateAllDemonstrations()}};ie.utils={};ie.utils.reconstructP2pkhScript=function(e){return S1.Script.buildPublicKeyHashOut(e).toHex()};ie.utils.createCovenantAddress=function(e){var t=S1.crypto.Hash.sha256ripemd160(e.toBuffer());return S1.Address.fromScriptHash(t)};ie.utils.decodeCompactSize=function(e,t){return ie.Preimage.decodeCompactSize(e,t)};ie.version=Km();ie.description="Smart Contract Framework for Bitcoin SV";ie.features={BIP143_PREIMAGE:!0,COMPACT_SIZE_VARINT:!0,BIDIRECTIONAL_EXTRACTION:!0,SIGHASH_DETECTION:!0,ZERO_HASH_WARNINGS:!0,MULTI_FIELD_VALIDATION:!0,REAL_UTXO_GENERATION:!0,SCRIPT_TESTING:!0,LOCAL_VERIFICATION:!0,JAVASCRIPT_TO_SCRIPT:!0,OPCODE_MAPPING:!0,COVENANT_BUILDER:!0,SCRIPT_ANALYSIS:!0,SCRIPT_OPTIMIZATION:!0,SCRIPT_CONVERSION:!0,BATCH_TESTING:!0,QUICK_COVENANTS:!0,SCRIPT_EXPLANATIONS:!0,STACK_EXAMINATION:!0,SCRIPT_DEBUGGING:!0,STEP_BY_STEP_EXECUTION:!0,INTERACTIVE_DEBUGGING:!0};ie.interpretScript=ie.debugScriptExecution;ie.getScriptMetrics=ie.scriptMetrics;SC.exports=ie});var EC=k((pve,x1)=>{"use strict";v();var W6=function(){var e=typeof A.default<"u"&&A.default.env&&A.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)},Xa={MEMORY:"memory",SESSION:"session",LOCAL:"local"};function xi(e){e=e||{},this.options={storage:e.storage||Xa.MEMORY,storageKey:e.storageKey||"smartledger-utxos",autoSave:e.autoSave!==!1,maxUTXOs:e.maxUTXOs||1e3};var t=[Xa.MEMORY,Xa.SESSION,Xa.LOCAL];if(t.indexOf(this.options.storage)===-1)throw new Error("Invalid storage type: "+this.options.storage);this.utxos=new Map,this.addressIndex=new Map,this.spentUTXOs=new Map,this.metadata={totalUTXOs:0,totalValue:0,createdAt:new Date().toISOString(),lastModified:new Date().toISOString()},this.loadFromStorage()}xi.prototype.getStorage=function(){return this.options.storage===Xa.SESSION?typeof sessionStorage<"u"?sessionStorage:null:this.options.storage===Xa.LOCAL&&typeof localStorage<"u"?localStorage:null};xi.prototype.loadFromStorage=function(){var e=this.getStorage();if(e)try{var t=e.getItem(this.options.storageKey);if(!t)return;var r=JSON.parse(t);if(!r.utxos)return;var i=this;r.utxos.forEach(function(n){var o=n.txid+":"+n.vout;i.utxos.set(o,n),i.addressIndex.has(n.address)||i.addressIndex.set(n.address,new Set),i.addressIndex.get(n.address).add(o)}),r.metadata&&(this.metadata=r.metadata),W6("\u2705 BrowserUTXOManager: Loaded "+this.utxos.size+" UTXOs from "+this.options.storage+" storage")}catch(n){console.error("Failed to load UTXOs from storage:",n)}};xi.prototype.saveToStorage=function(){if(this.options.storage!==Xa.MEMORY){var e=this.getStorage();if(e)try{var t={utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",timestamp:new Date().toISOString()};e.setItem(this.options.storageKey,JSON.stringify(t)),W6("\u{1F4BE} BrowserUTXOManager: Saved "+this.utxos.size+" UTXOs to "+this.options.storage+" storage")}catch(r){console.error("Failed to save UTXOs to storage:",r)}}};xi.prototype.addUTXO=function(e){if(!e||!e.txid||typeof e.vout!="number")throw new Error("Invalid UTXO: missing txid or vout");var t=e.txid+":"+e.vout;if(this.utxos.has(t))return W6("\u26A0\uFE0F UTXO already exists: "+t),!1;var r={txid:e.txid,vout:e.vout,address:e.address||"",satoshis:e.satoshis||0,script:e.script||"",status:"available",addedAt:new Date().toISOString()};return this.utxos.set(t,r),r.address&&(this.addressIndex.has(r.address)||this.addressIndex.set(r.address,new Set),this.addressIndex.get(r.address).add(t)),this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),!0};xi.prototype.getUTXOsForAddress=function(e){var t=this.addressIndex.get(e);if(!t)return[];var r=[],i=this;return t.forEach(function(n){var o=i.utxos.get(n);o&&o.status==="available"&&r.push(o)}),r};xi.prototype.getBalance=function(e){var t=this.getUTXOsForAddress(e);return t.reduce(function(r,i){return r+(i.satoshis||0)},0)};xi.prototype.spendUTXOs=function(e,t){t=t||"browser-spend";for(var r=[],i=0;i<e.length;i++){var n=e[i],o=n.txid+":"+n.vout,a=this.utxos.get(o);a&&a.status==="available"&&(a.status="spent",a.spentAt=new Date().toISOString(),a.spentInTx=t,this.spentUTXOs.set(o,{txid:a.txid,vout:a.vout,spentInTx:t,spentAt:a.spentAt}),r.push(a))}return this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),r};xi.prototype.getUTXO=function(e,t){var r=e+":"+t,i=this.utxos.get(r);return{exists:!!i,utxo:i,status:i?i.status:"not-found"}};xi.prototype.createMockUTXOs=function(e,t,r){t=t||5,r=r||1e5;for(var i=[],n=0;n<t;n++){for(var o="",a=0;a<64;a++)o+=Math.floor(Math.random()*16).toString(16);var s={txid:o,vout:n,address:e,satoshis:r+Math.floor(Math.random()*1e4),script:"",status:"available"};this.addUTXO(s),i.push(s)}return i};xi.prototype.getStats=function(){var e=0,t=0,r=0;return this.utxos.forEach(function(i){e+=i.satoshis||0,i.status==="available"?t++:i.status==="spent"&&r++}),{totalUTXOs:this.utxos.size,totalAvailable:t,totalSpent:r,totalValue:e,totalAddresses:this.addressIndex.size,storageType:this.options.storage,metadata:this.metadata}};xi.prototype.updateMetadata=function(){var e=this.getStats();this.metadata.totalUTXOs=e.totalUTXOs,this.metadata.totalValue=e.totalValue,this.metadata.lastModified=new Date().toISOString()};xi.prototype.exportData=function(){return JSON.stringify({utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",exportedAt:new Date().toISOString()})};xi.prototype.importData=function(e,t){t=t||!1;try{var r=JSON.parse(e);if(t||(this.utxos.clear(),this.addressIndex.clear(),this.spentUTXOs.clear()),r.utxos&&Array.isArray(r.utxos)){var i=this;r.utxos.forEach(function(n){i.addUTXO(n)})}return W6("\u2705 BrowserUTXOManager: Imported "+(r.utxos&&r.utxos.length||0)+" UTXOs"),!0}catch(n){return console.error("Failed to import UTXO data:",n),!1}};typeof x1<"u"&&x1.exports?(x1.exports=xi,x1.exports.STORAGE_TYPES=Xa):typeof window<"u"&&(window.BrowserUTXOManager=xi,window.BrowserUTXOManager.STORAGE_TYPES=Xa)});var IC=k((vve,OC)=>{"use strict";v();var t7=class{constructor(t,r={}){this.bsv=t,this.options={difficulty:r.difficulty||1,blockTime:r.blockTime||1e4,validateScripts:r.validateScripts!==!1,logLevel:r.logLevel||"info",...r},this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[]}acceptTransaction(t){try{return this.options.validateScripts&&!this.validateTransactionSignatures(t)?(this.log("warn","\u274C Transaction rejected: Invalid signatures"),!1):(this.mempool.push(t),this.log("info",`\u2705 Transaction accepted into mempool: ${t.id||"unknown"}`),!0)}catch(r){return this.log("error",`\u274C Transaction rejected: ${r.message}`),!1}}validateTransactionSignatures(t){try{let r=t.verify();return this.log("debug",`\u{1F4CA} Transaction verification result: ${r}`),r===!0}catch(r){return this.log("warn",`\u26A0\uFE0F Signature validation error: ${r.message}`),!1}}mineBlock(t=10){let r=this.mempool.splice(0,t),i={height:this.currentBlock.height+1,timestamp:Date.now(),transactions:r,transactionCount:r.length,previousBlockHash:this.currentBlock.hash||"0000000000000000000000000000000000000000000000000000000000000000"},n=JSON.stringify({height:i.height,timestamp:i.timestamp,previousBlockHash:i.previousBlockHash,transactions:r.map(o=>o.id||o.toString())});return i.hash=this.bsv.crypto.Hash.sha256(h.Buffer.from(n)).toString("hex"),this.currentBlock=i,this.log("info",`\u26CF\uFE0F Mined block ${i.height} with ${r.length} transactions`),this.log("debug",`\u{1F4E6} Block hash: ${i.hash}`),i}getMempoolStats(){return{transactionCount:this.mempool.length,transactions:this.mempool.map(t=>({id:t.id||"unknown",size:t.toBuffer?t.toBuffer().length:0,inputs:t.inputs?t.inputs.length:0,outputs:t.outputs?t.outputs.length:0}))}}getBlockchainStats(){return{currentHeight:this.currentBlock.height,currentBlockHash:this.currentBlock.hash,currentBlockTimestamp:this.currentBlock.timestamp,mempoolSize:this.mempool.length,difficulty:this.options.difficulty,blockTime:this.options.blockTime}}reset(){this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[],this.log("info","\u{1F504} Miner reset to genesis state")}log(t,r){let i={error:0,warn:1,info:2,debug:3},n=i[this.options.logLevel]||2;if(i[t]<=n){let o=new Date().toISOString();console.log(`[${o}] [${t.toUpperCase()}] ${r}`)}}};OC.exports=t7});var PC=k((yve,AC)=>{v();var Ne=Te(),Bl=class{static createSignature(t,r,i,n,o,a=null){a=a||Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID;let s=Ne.Transaction.sighash.sign(t,r,a,i,n,new Ne.crypto.BN(o));return h.Buffer.concat([s.toDER(),h.Buffer.from([a])])}static createMultisigScript(t,r){let i=new Ne.Script().add(Ne.Opcode[`OP_${t}`]);for(let n of r)i=i.add(n.toBuffer());return i.add(Ne.Opcode[`OP_${r.length}`]).add(Ne.Opcode.OP_CHECKMULTISIG)}static createMultisigUnlocking(t){let r=new Ne.Script().add(Ne.Opcode.OP_0);for(let i of t)r=r.add(i);return r}static createTimelockScript(t,r){let i=h.Buffer.from(t.toString(16).padStart(8,"0"),"hex").reverse();return new Ne.Script().add(i).add(Ne.Opcode.OP_CHECKLOCKTIMEVERIFY).add(Ne.Opcode.OP_DROP).add(r.toBuffer())}static createConditionalScript(t,r=null){let i=new Ne.Script().add(Ne.Opcode.OP_IF).add(t.toBuffer());return r&&(i=i.add(Ne.Opcode.OP_ELSE).add(r.toBuffer())),i.add(Ne.Opcode.OP_ENDIF)}static createP2PKHScript(t){return new Ne.Script().add(Ne.Opcode.OP_DUP).add(Ne.Opcode.OP_HASH160).add(t.toAddress().hashBuffer).add(Ne.Opcode.OP_EQUALVERIFY).add(Ne.Opcode.OP_CHECKSIG)}static createP2PKHUnlocking(t,r){return new Ne.Script().add(t).add(r.toBuffer())}static getPreimage(t,r,i,n,o=null){return o=o||Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID,Ne.Transaction.sighash.sighash(t,o,r,i,new Ne.crypto.BN(n))}static createDataScript(t){return typeof t=="string"&&(t=h.Buffer.from(t,"utf8")),new Ne.Script().add(t)}static createOpReturnScript(t){return typeof t=="string"&&(t=h.Buffer.from(t,"utf8")),new Ne.Script().add(Ne.Opcode.OP_FALSE).add(Ne.Opcode.OP_RETURN).add(t)}static validateTransaction(t){try{return t.verify()}catch(r){return console.error("Transaction validation error:",r.message),!1}}static validateScript(t,r,i,n){try{return new Ne.Script.Interpreter().verify(t,r,i,n,Ne.Script.Interpreter.SCRIPT_VERIFY_P2SH|Ne.Script.Interpreter.SCRIPT_VERIFY_STRICTENC|Ne.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID|Ne.Script.Interpreter.SCRIPT_ENABLE_MAGNETIC_OPCODES|Ne.Script.Interpreter.SCRIPT_ENABLE_MONOLITH_OPCODES)}catch(o){return console.error("Script validation error:",o.message),!1}}static createLowFeeTransaction(t,r,i=10){let n=new Ne.Transaction().feePerKb(i);for(let o of t)n=n.from(o);for(let o of r)n=n.to(o.address,o.satoshis);return n}};Bl.SIGHASH_ALL=Ne.crypto.Signature.SIGHASH_ALL|Ne.crypto.Signature.SIGHASH_FORKID;Bl.SIGHASH_NONE=Ne.crypto.Signature.SIGHASH_NONE|Ne.crypto.Signature.SIGHASH_FORKID;Bl.SIGHASH_SINGLE=Ne.crypto.Signature.SIGHASH_SINGLE|Ne.crypto.Signature.SIGHASH_FORKID;AC.exports=Bl});var Y6=k((_ve,CC)=>{"use strict";v();var O1=Te(),kC=h.Buffer.from("ord","utf8");function r7(){return O1.Script}function RC(){return O1.Opcode}function BC(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"an array";var t=typeof e;return(t==="object"?"an ":"a ")+t}function TC(e,t){if(h.Buffer.isBuffer(e))return e;if(typeof e=="string")return h.Buffer.from(e,"utf8");throw new Error(t+" must be a string or Buffer, got "+BC(e))}var eoe=["data","body","payload","text","message"];function toe(e){var t=r7(),r=e.lock!=null,i=e.address!=null;if(r&&i)throw new Error("buildInscription accepts `lock` or `address`, not both \u2014 they name different owners and one would be silently ignored");if(r){var n;if(e.lock instanceof t)n=e.lock;else if(h.Buffer.isBuffer(e.lock))n=t.fromBuffer(e.lock);else if(typeof e.lock=="string")n=t.fromHex(e.lock);else throw new Error("lock must be a Script, Buffer, or hex string, got "+BC(e.lock));if(!n.chunks.length&&!e.allowEmptyLock)throw new Error("lock is empty: the inscription would carry no locking script at all and the ordinal would be spendable by anyone. Pass a real lock, or { allowEmptyLock: true } if you are appending this envelope to your own script");return n}if(i){var o=e.address instanceof O1.Address?e.address:O1.Address.fromString(String(e.address));return t.buildPublicKeyHashOut(o)}throw new Error("buildInscription requires an address or a lock script")}function MC(e){e=e||{};var t=RC(),r=toe(e);if(e.content==null){var i=eoe.filter(function(s){return e[s]!=null})[0];throw new Error("buildInscription requires `content`"+(i?" \u2014 received `"+i+"`, which is not read":"")+". Omitting it would inscribe an empty payload; pass content: '' if that is intended")}var n=TC(e.content,"content"),o;if(e.contentType==null){if(h.Buffer.isBuffer(e.content))throw new Error("contentType is required when content is a Buffer (e.g. 'image/png', 'application/octet-stream') \u2014 it cannot be inferred from bytes");o=h.Buffer.from("text/plain","utf8")}else if(o=TC(e.contentType,"contentType"),!o.length)throw new Error("contentType must not be empty");var a=r7().fromBuffer(r.toBuffer());return a.add(t.OP_FALSE),a.add(t.OP_IF),a.add(kC),a.add(t.OP_1),a.add(o),a.add(t.OP_0),a.add(n),a.add(t.OP_ENDIF),a}function E1(e,t){return e&&e.opcodenum===t&&e.buf==null}function NC(e){for(var t=r7(),r=RC(),i=e instanceof t?e:h.Buffer.isBuffer(e)?t.fromBuffer(e):t.fromHex(e),n=i.chunks,o=-1,a=0;a+2<n.length;a++)if(E1(n[a],r.OP_FALSE)&&E1(n[a+1],r.OP_IF)&&n[a+2].buf&&n[a+2].buf.equals(kC)){o=a;break}if(o===-1)return null;for(var s=h.Buffer.alloc(0),u=h.Buffer.alloc(0),c=n.length,l=o+3;l<n.length;l++){var m=n[l];if(E1(m,r.OP_ENDIF)){c=l;break}E1(m,r.OP_1)&&n[l+1]&&n[l+1].buf?(s=n[l+1].buf,l++):E1(m,r.OP_0)&&n[l+1]&&n[l+1].buf&&(u=n[l+1].buf,l++)}for(var w=new t,E=0;E<o;E++)w.chunks.push(n[E]);for(var P=c+1;P<n.length;P++)w.chunks.push(n[P]);return{contentType:s.toString("utf8"),content:u,contentText:u.toString("utf8"),lock:w}}function roe(e){try{return NC(e)!==null}catch{return!1}}function ioe(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new Error("satoshis must be a positive integer (1 for a standard 1Sat ordinal)");return new O1.Transaction.Output({script:MC(e),satoshis:t})}CC.exports={buildInscription:MC,parseInscription:NC,isInscription:roe,createInscriptionOutput:ioe}});var zC=k((Sve,jC)=>{"use strict";v();var qr=Te(),Nl=Tl(),i7=Go(),qC=Y6(),Yo=qr.Script,Xt=qr.Opcode,UC=qr.encoding.BufferReader,J6=Nl.SIGHASH_ALL_ANYONECANPAY_FORKID;function DC(e,t){return t&&t.length?e.add(h.Buffer.from(t)):e.add(Xt.OP_0)}function $6(e){return e.toBufferWriter().toBuffer()}function Cl(e,t){if(typeof e!="number"||!isFinite(e)||e<0||Math.floor(e)!==e)throw new Error(t+" must be a non-negative integer number of satoshis (got "+e+")");return e}function e5(e){return e instanceof Yo?e:h.Buffer.isBuffer(e)?Yo.fromBuffer(e):Yo.fromHex(e)}function FC(e){return e instanceof qr.Address?e:e&&typeof e.toAddress=="function"?e.toAddress():qr.Address.fromString(String(e))}function noe(e){if(h.Buffer.isBuffer(e)){if(e.length!==20)throw new Error("seller pubkeyhash buffer must be 20 bytes (HASH160)");return e}return e instanceof qr.PublicKey?qr.crypto.Hash.sha256ripemd160(e.toBuffer()):FC(e).hashBuffer}function Dl(e,t){return Cl(t,"payment price"),new qr.Transaction.Output({script:Yo.buildPublicKeyHashOut(FC(e)),satoshis:t})}function X6(e){if(e instanceof qr.Transaction.Output)return e;if(h.Buffer.isBuffer(e))return qr.Transaction.Output.fromBufferReader(new UC(e));var t=e.payTo!=null?e.payTo:e.address,r=e.satoshis!=null?e.satoshis:e.price;if(t==null||r==null)throw new Error("payment spec needs {address|payTo, satoshis|price}");return Dl(t,r)}function ooe(e){if(e.payOutputs){if(!e.payOutputs.length)throw new Error("payOutputs must be a non-empty array");return e.payOutputs.map(X6)}if(e.payOutput!=null)return[X6(e.payOutput)];if(e.price!=null){var t=e.payTo!=null?e.payTo:e.seller,r=t instanceof qr.Transaction.Output?t:Dl(t,e.price),i=[r];return e.royalties&&e.royalties.forEach(function(n){i.push(X6(n))}),i}throw new Error("buildOrdLock requires a price, a payOutput, or payOutputs")}function aoe(e){return h.Buffer.concat(e.map($6))}function t5(e){if(e=e||{},e.seller==null)throw new Error("buildOrdLock requires a seller");var t=noe(e.seller),r=aoe(ooe(e)),i=new Yo;if(i.add(Xt.OP_IF),i.add(Xt.OP_DUP).add(Xt.OP_HASH160),i.add(h.Buffer.from(t)).add(Xt.OP_EQUALVERIFY).add(Xt.OP_CHECKSIG),i.add(Xt.OP_ELSE),i.add(Xt.OP_DUP),Nl.pushTxCore(i,{sighashType:J6}),i.add(Xt.OP_VERIFY),Nl.assertSighashType(i,J6),Nl.extractHashOutputs(i),i.add(Xt.OP_TOALTSTACK),i.add(h.Buffer.from(r)).add(Xt.OP_CAT),i.add(Xt.OP_SWAP).add(Xt.OP_CAT),i.add(Xt.OP_HASH256),i.add(Xt.OP_FROMALTSTACK).add(Xt.OP_EQUAL),i.add(Xt.OP_ENDIF),e.inscription){var n=qC.buildInscription({lock:new Yo,allowEmptyLock:!0,contentType:e.inscription.contentType,content:e.inscription.content});n.chunks.forEach(function(o){i.chunks.push(o)})}return i}function Ml(e,t){return e&&e.opcodenum===t&&e.buf==null}function LC(e){for(var t=new UC(e),r=[];!t.eof();)r.push(qr.Transaction.Output.fromBufferReader(t));return r}function r5(e,t){var r=t&&t.network;try{for(var i=e5(e),n=i.chunks,o=0,a=-1,s=-1,u=-1,c=0;c<n.length;c++)if(Ml(n[c],Xt.OP_IF))o===0&&(a=c),o++;else if(Ml(n[c],Xt.OP_ELSE)&&o===1)s=c;else if(Ml(n[c],Xt.OP_ENDIF)&&(o--,o===0)){u=c;break}if(a===-1||s===-1||u===-1)return null;for(var l=null,m=a+1;m<s;m++)if(n[m].buf&&n[m].buf.length===20){l=n[m].buf;break}if(!l)return null;for(var w=null,E=s+1;E<u;E++)Ml(n[E],Xt.OP_TOALTSTACK)&&n[E+1]&&n[E+1].buf&&Ml(n[E+2],Xt.OP_CAT)&&Ml(n[E+3],Xt.OP_SWAP)&&(w=n[E+1].buf);if(!w)return null;var P=LC(w).map(function(K){var N=null;try{K.script.isPublicKeyHashOut()&&(N=K.script.toAddress(r).toString())}catch{}return{satoshis:K.satoshis,script:K.script,address:N}}),M=P.reduce(function(K,N){return K+N.satoshis},0),D=null,L=qC.parseInscription(i);L&&(D={contentType:L.contentType,content:L.content,contentText:L.contentText});var U=t5({seller:l,payOutputs:LC(w),inscription:L?{contentType:L.contentType,content:L.content}:void 0});return U.toHex()!==i.toHex()?null:{seller:{pubKeyHash:l,address:qr.Address.fromPublicKeyHash(l,r).toString()},payOutputs:P,payBlob:w,totalPrice:M,inscription:D}}catch{return null}}function soe(e,t){return r5(e,t)!==null}function uoe(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;return new qr.Transaction.Output({script:t5(e),satoshis:t})}function HC(e){e=e||{};var t=e.spend,r=e.lockingScript;if(!t||!r)throw new Error("purchase requires { spend, lockingScript }");var i=e.inputIndex||0,n=e.payoutIndex!=null?e.payoutIndex:1,o=e.satoshis!=null?e.satoshis:1,a=t.outputs||[],s=e.parsed||r5(r),u=e.payoutCount!=null?e.payoutCount:s?s.payOutputs.length:1;if(n+u>a.length)throw new Error("purchase: spend has fewer outputs than the pinned block requires (need "+(n+u)+", have "+a.length+")");if(e.validate!==!1&&s){var c=h.Buffer.concat(a.slice(n,n+u).map($6));if(!c.equals(s.payBlob))throw new Error("purchase: outputs ["+n+".."+(n+u-1)+"] do not match the listing payment \u2014 the seller (or a royalty/fee payee) would not be paid")}var l=h.Buffer.concat(a.slice(0,n).map($6)),m=h.Buffer.concat(a.slice(n+u).map($6)),w=Object.assign({sighashType:J6},e.grind||{}),E=Nl.grind(t,i,r,o,w),P=new Yo;return DC(P,m),DC(P,l),P.add(h.Buffer.from(E.preimage)),P.add(Xt.OP_FALSE),t.inputs[i].setScript(P),P}function foe(e){e=e||{};var t=e.privateKey,r=e.spend,i=e.lockingScript;if(!t||!r||!i)throw new Error("cancel requires { privateKey, spend, lockingScript }");var n=e.inputIndex||0,o=e.satoshis!=null?e.satoshis:1,a=e.sighashType!=null?e.sighashType:i7.SIGHASH,s=i7.signInput(r,t,n,i,o,a),u=new Yo;return u.add(h.Buffer.from(s)),u.add(t.toPublicKey().toBuffer()),u.add(Xt.OP_TRUE),r.inputs[n].setScript(u),u}function Q6(e,t,r,i){e.addInput(new qr.Transaction.Input({prevTxId:t.txid||t.prevTxId,outputIndex:t.outputIndex!=null?t.outputIndex:t.vout,script:Yo.empty()}),e5(r),i)}function n7(e,t,r){Cl(r.satoshis,"input "+t+" satoshis");var i=e5(r.script),n=i7.signInput(e,r.privateKey,t,i,r.satoshis,Nl.SIGHASH_ALL_FORKID),o=new Yo;o.add(h.Buffer.from(n)),o.add(r.privateKey.toPublicKey().toBuffer()),e.inputs[t].setScript(o)}function coe(e){e=e||{};var t=e.ordinal;if(!t||!t.script||!t.privateKey)throw new Error("buildListingTx requires ordinal { script, privateKey, txid, outputIndex }");var r=Cl(t.satoshis!=null?t.satoshis:1,"ordinal satoshis"),i=t5(e),n=e.funding||[],o=e.fee!=null?e.fee:500,a=n.reduce(function(c,l){return c+Cl(l.satoshis,"funding satoshis")},0),s=a-o;if(s<0)throw new Error("buildListingTx: insufficient funding \u2014 need "+o+" sat fee, funded "+a);var u=new qr.Transaction;return Q6(u,t,t.script,r),n.forEach(function(c){Q6(u,c,c.script,c.satoshis)}),u.addOutput(new qr.Transaction.Output({script:i,satoshis:r})),s>0&&u.addOutput(Dl(e.changeAddress||t.privateKey.toAddress(),s)),n7(u,0,{script:t.script,privateKey:t.privateKey,satoshis:r}),n.forEach(function(c,l){n7(u,1+l,c)}),{tx:u,listingScript:i,listingOutpoint:{txid:u.hash,outputIndex:0}}}function loe(e){e=e||{};var t=e.listing;if(!t||!t.script)throw new Error("buildPurchaseTx requires listing.script");if(!e.ordinalDestination)throw new Error("buildPurchaseTx requires ordinalDestination");if(!e.funding||!e.funding.length)throw new Error("buildPurchaseTx requires funding coins");var r=e5(t.script),i=r5(r);if(!i)throw new Error("buildPurchaseTx: listing.script is not a parseable OrdLock");var n=Cl(t.satoshis!=null?t.satoshis:1,"listing satoshis"),o=e.payOutputs?e.payOutputs.map(X6):i.payOutputs.map(function(m){return new qr.Transaction.Output({script:m.script,satoshis:m.satoshis})}),a=o.reduce(function(m,w){return m+w.satoshis},0),s=e.fee!=null?e.fee:500,u=e.funding.reduce(function(m,w){return m+Cl(w.satoshis,"funding satoshis")},0),c=u-a-s;if(c<0)throw new Error("buildPurchaseTx: insufficient funding \u2014 need "+(a+s)+" sat (payments "+a+" + fee "+s+"), funded "+u);var l=new qr.Transaction;return Q6(l,t,r,n),e.funding.forEach(function(m){Q6(l,m,m.script,m.satoshis)}),l.addOutput(Dl(e.ordinalDestination,n)),o.forEach(function(m){l.addOutput(m)}),c>0&&l.addOutput(Dl(e.changeAddress||e.ordinalDestination,c)),HC({spend:l,lockingScript:r,parsed:i,satoshis:n,inputIndex:0,payoutIndex:1,payoutCount:o.length,grind:e.grind}),e.funding.forEach(function(m,w){n7(l,1+w,m)}),l}jC.exports={ORDLOCK_SIGHASH:J6,buildOrdLock:t5,parseOrdLock:r5,isOrdLock:soe,listInscriptionOutput:uoe,payOutputFor:Dl,purchase:HC,cancel:foe,buildListingTx:coe,buildPurchaseTx:loe}});var uD=k((Eve,sD)=>{"use strict";v();var KC=Y6(),VC="application/bsv-20",o7=18,i5="18446744073709551615";function GC(e){return typeof e=="string"&&/^\d+$/.test(e)}function ZC(e){return e.length>i5.length||e.length===i5.length&&e>i5}function WC(e,t){var r;if(typeof e=="number"){if(!Number.isInteger(e)||e<0)throw new Error(t+" must be a non-negative integer");if(e>Number.MAX_SAFE_INTEGER)throw new Error(t+" exceeds Number.MAX_SAFE_INTEGER and would lose precision \u2014 pass it as a string");r=String(e)}else if(GC(e))r=e.replace(/^0+(?=\d)/,"");else throw new Error(t+" must be a non-negative integer (string or number)");if(ZC(r))throw new Error(t+" exceeds the uint64 maximum ("+i5+")");return r}function I1(e,t){var r=WC(e,t);if(!/[1-9]/.test(r))throw new Error(t+" must be greater than zero");return r}function YC(e){if(typeof e!="string"||!e.length)throw new Error("tick is required");if(h.Buffer.byteLength(e,"utf8")>4)throw new Error("tick must be 1\u20134 UTF-8 bytes");return e}function a7(e){var t=typeof e=="string"?Number(e):e;if(!Number.isInteger(t)||t<0||t>o7)throw new Error("dec must be an integer 0\u2026"+o7);return String(t)}var s7=/^[0-9a-fA-F]{64}_\d+$/;function u7(e){if(typeof e!="string"||!s7.test(e))throw new Error('id must be "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function f7(e,t){if(typeof e!="string"){var r=e===null?"null":Array.isArray(e)?"an array":(typeof e=="object"?"an ":"a ")+typeof e;throw new Error(t+" must be a string, got "+r)}if(!e.length)throw new Error(t+" must not be empty");return e}function $C(e){if(f7(e,"icon"),!s7.test(e))throw new Error('icon must be an outpoint reference "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function If(e,t){return t=t||{},KC.buildInscription({lock:t.lock,address:t.address,contentType:t.contentType||VC,content:JSON.stringify(e)})}function XC(e){e=e||{};var t={p:"bsv-20",op:"deploy",tick:YC(e.tick),max:I1(e.max,"max")};return e.lim!=null&&(t.lim=WC(e.lim,"lim")),e.dec!=null&&(t.dec=a7(e.dec)),If(t,e)}function JC(e,t,r){var i=t.tick!=null,n=t.id!=null;if(i&&n)throw new Error(r+" names a token by `tick` (v1) or `id` (BSV-21), not both");if(!i&&!n)throw new Error(r+" requires `tick` (v1) or `id` (BSV-21)");return n?e.id=u7(t.id):e.tick=YC(t.tick),e}function QC(e,t){if(e.amt!=null)throw new Error(t+" must not carry an amt \u2014 the specification forbids it, and a payload that does is discarded")}function eD(e){e=e||{};var t={p:"bsv-20",op:"mint"};return JC(t,e,"mint"),t.amt=I1(e.amt,"amt"),If(t,e)}function tD(e){e=e||{};var t={p:"bsv-20",op:"transfer",amt:I1(e.amt,"amt")};return JC(t,e,"transfer"),If(t,e)}function rD(e){if(e=e||{},e.tick!=null)throw new Error("burn is a BSV-21 operation and names its token by `id` (<txid>_<vout>), not `tick`");var t={p:"bsv-20",op:"burn",id:u7(e.id),amt:I1(e.amt,"amt")};return If(t,e)}function iD(e){e=e||{},QC(e,"deploy+auth");var t={p:"bsv-20",op:"deploy+auth"};return e.dec!=null&&(t.dec=a7(e.dec)),e.sym!=null&&(t.sym=f7(e.sym,"sym")),e.icon!=null&&(t.icon=$C(e.icon)),If(t,e)}function nD(e){e=e||{},QC(e,"auth");var t={p:"bsv-20",op:"auth",id:u7(e.id)};return If(t,e)}function oD(e){e=e||{};var t={p:"bsv-20",op:"deploy+mint",amt:I1(e.amt,"amt")};return e.dec!=null&&(t.dec=a7(e.dec)),e.sym!=null&&(t.sym=f7(e.sym,"sym")),e.icon!=null&&(t.icon=$C(e.icon)),If(t,e)}function Af(e,t){var r=Te();return new r.Transaction.Output({script:e,satoshis:t??1})}function hoe(e){return Af(XC(e),e&&e.satoshis)}function doe(e){return Af(eD(e),e&&e.satoshis)}function poe(e){return Af(tD(e),e&&e.satoshis)}function goe(e){return Af(oD(e),e&&e.satoshis)}function voe(e){return Af(rD(e),e&&e.satoshis)}function moe(e){return Af(iD(e),e&&e.satoshis)}function yoe(e){return Af(nD(e),e&&e.satoshis)}function boe(e){var t=Te();if(e&&typeof e=="object"&&!h.Buffer.isBuffer(e)&&!(e instanceof t.Script)||typeof e=="string"&&e.trim()[0]==="{")return e;var r=KC.parseInscription(e);return r?r.contentText:null}var _oe={deploy:{need:["tick","max"]},mint:{need:["amt"],tickOrId:!0},transfer:{need:["amt"],tickOrId:!0},"deploy+mint":{need:["amt"]},"deploy+auth":{need:[],noAmt:!0},auth:{need:["id"],noAmt:!0},burn:{need:["id","amt"]}};function woe(e){var t=typeof e=="number"?Number.isInteger(e)&&e>=0?String(e):null:GC(e)?e:null;return t==null?!1:!ZC(t.replace(/^0+(?=\d)/,""))}function Soe(e){if(!e||e.p!=="bsv-20"||typeof e.op!="string")return!1;var t=_oe[e.op];if(!t)return!1;for(var r=0;r<t.need.length;r++)if(e[t.need[r]]==null)return!1;if(t.tickOrId&&e.tick==null==(e.id==null)||t.noAmt&&e.amt!=null||e.tick!=null&&(typeof e.tick!="string"||!e.tick.length||h.Buffer.byteLength(e.tick,"utf8")>4)||e.id!=null&&(typeof e.id!="string"||!s7.test(e.id)))return!1;for(var i=["amt","max","lim"],n=0;n<i.length;n++)if(e[i[n]]!=null&&!woe(e[i[n]]))return!1;if(e.dec!=null){var o=typeof e.dec=="string"?Number(e.dec):e.dec;if(!Number.isInteger(o)||o<0||o>o7)return!1}return!0}function aD(e){try{var t=boe(e);if(t==null)return null;var r=typeof t=="object"?t:JSON.parse(t);return Soe(r)?r:null}catch{return null}}function xoe(e){return aD(e)!==null}sD.exports={CONTENT_TYPE:VC,buildDeploy:XC,buildMint:eD,buildTransfer:tD,buildDeployMint:oD,buildBurn:rD,buildDeployAuth:iD,buildAuth:nD,createDeployOutput:hoe,createMintOutput:doe,createTransferOutput:poe,createDeployMintOutput:goe,createBurnOutput:voe,createDeployAuthOutput:moe,createAuthOutput:yoe,parseBsv20:aD,isBsv20:xoe}});var cD=k((Ive,fD)=>{"use strict";v();var A1=Y6(),$o=zC(),Eoe=uD();function Ooe(e){if(!Array.isArray(e)||!e.length)throw new Error("batchInscriptionOutputs requires a non-empty array of items");return e.map(function(t){return A1.createInscriptionOutput(t)})}fD.exports={buildInscription:A1.buildInscription,parseInscription:A1.parseInscription,isInscription:A1.isInscription,createInscriptionOutput:A1.createInscriptionOutput,batchInscriptionOutputs:Ooe,ORDLOCK_SIGHASH:$o.ORDLOCK_SIGHASH,buildOrdLock:$o.buildOrdLock,parseOrdLock:$o.parseOrdLock,isOrdLock:$o.isOrdLock,listInscriptionOutput:$o.listInscriptionOutput,payOutputFor:$o.payOutputFor,purchaseOrdLock:$o.purchase,cancelOrdLock:$o.cancel,buildListingTx:$o.buildListingTx,buildPurchaseTx:$o.buildPurchaseTx,BSV20:Eoe}});var hD=k((Pve,lD)=>{"use strict";v();var n5=_r();async function Ioe(e){e=e||{};var t=e.alg||"ES256",r=e.kid||"key-"+Date.now();if(t!=="ES256"&&t!=="ES256K")throw new Error("Invalid algorithm. Must be ES256 or ES256K");var i;t==="ES256"?i=n5.generateKeyPairSync("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}):i=n5.generateKeyPairSync("ec",{namedCurve:"secp256k1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});var n=n5.createPublicKey(i.publicKey).export({format:"jwk"}),o=n5.createPrivateKey(i.privateKey).export({format:"jwk"});return n.kid=r,n.alg=t,n.use="sig",n.kty="EC",o.kid=r,o.alg=t,o.use="sig",o.kty="EC",{privateJwk:o,publicJwk:n,kid:r,alg:t}}function Aoe(e){if(!e.domain)throw new Error("domain is required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=[],n=[];if(e.p256){var o={id:r+"#"+e.p256.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.p256.jwk};i.push(o),n.push(e.p256.jwk)}if(e.k1){var a={id:r+"#"+e.k1.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.k1.jwk};i.push(a),n.push(e.k1.jwk)}if(i.length===0)throw new Error("At least one key (p256 or k1) must be provided");var s={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:i,authentication:i.map(function(c){return c.id}),assertionMethod:i.map(function(c){return c.id})};e.controllerName&&(s.controller=e.controllerName);var u={keys:n};return{did:r,didDocument:s,jwks:u}}function Poe(e){if(!e.domain||!e.newKey)throw new Error("domain and newKey are required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=e.keepOldForDays||30,n={id:r+"#"+e.newKey.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.newKey.jwk},o={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:[n],authentication:[n.id],assertionMethod:[n.id],rotationInfo:{rotatedAt:new Date().toISOString(),gracePeriodDays:i}},a={keys:[e.newKey.jwk]};return{didDocument:o,jwks:a}}lD.exports={generateIssuerKeys:Ioe,buildDidWebDocuments:Aoe,rotateIssuerKey:Poe}});var c7=k((kve,dD)=>{"use strict";v();var P1=_r(),T1={ES256:"P-256",ES256K:"secp256k1"},Toe=["ES256","ES256K"];function o5(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function a5(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return h.Buffer.from(e,"base64")}async function koe(e){if(!e.issuerDid||!e.subjectId||!e.credentialSubject||!e.privateJwk)throw new Error("issuerDid, subjectId, credentialSubject, and privateJwk are required");var t=e.alg||"ES256";if(!T1[t])throw new Error("Unsupported algorithm: "+t);if(e.privateJwk.crv&&e.privateJwk.crv!==T1[t])throw new Error("Key curve "+e.privateJwk.crv+" does not match alg "+t);var r=e.kid||e.privateJwk.kid,i=e.types||["VerifiableCredential"],n=e.expSeconds||365*24*60*60,o=Math.floor(Date.now()/1e3),a=new Date().toISOString(),s={"@context":["https://www.w3.org/2018/credentials/v1"],type:i,issuer:e.issuerDid,issuanceDate:a,credentialSubject:Object.assign({id:e.subjectId},e.credentialSubject)},u={iss:e.issuerDid,sub:e.subjectId,iat:o,exp:o+n,vc:s},c={alg:t,typ:"JWT",kid:r},l=o5(h.Buffer.from(JSON.stringify(c))),m=o5(h.Buffer.from(JSON.stringify(u))),w=l+"."+m,E=P1.createPrivateKey({key:e.privateJwk,format:"jwk"}),P=P1.sign("sha256",h.Buffer.from(w),{key:E,dsaEncoding:"ieee-p1363"}),M=o5(P),D=w+"."+M;return{jwt:D}}async function Roe(e,t){t=t||{};try{if(typeof e!="string")return{valid:!1,error:"Invalid JWT format"};var r=e.split(".");if(r.length!==3)return{valid:!1,error:"Invalid JWT format"};var i=r[0],n=r[1],o=r[2],a=JSON.parse(a5(i).toString()),s=JSON.parse(a5(n).toString()),u=a5(o),c=t.allowedAlgs||Toe;if(!a.alg||c.indexOf(a.alg)===-1||!T1[a.alg])return{valid:!1,error:"Algorithm not allowed: "+a.alg,header:a,payload:s};var l=Math.floor(Date.now()/1e3),m=t.clockToleranceSec||60;if(t.requireExpiration&&!s.exp)return{valid:!1,error:"JWT missing required exp claim",header:a,payload:s};if(s.exp&&s.exp<l-m)return{valid:!1,error:"JWT expired",header:a,payload:s};if(s.nbf&&s.nbf>l+m)return{valid:!1,error:"JWT not yet valid",header:a,payload:s};if(t.expectedIssuerDid&&s.iss!==t.expectedIssuerDid)return{valid:!1,error:"Unexpected issuer",header:a,payload:s};var w;if(t.didResolver){var E=await t.didResolver(s.iss);if(!E||!E.jwks||!E.jwks.keys)return{valid:!1,error:"Failed to resolve issuer DID",header:a,payload:s};var P=E.jwks.keys.find(function(U){return U.kid===a.kid});if(!P)return{valid:!1,error:"Key not found in JWKS",header:a,payload:s};w=P}else return{valid:!1,error:"DID resolver required for verification",header:a,payload:s};if(w.crv&&w.crv!==T1[a.alg])return{valid:!1,error:"Key curve does not match algorithm",header:a,payload:s};var M=i+"."+n,D=P1.createPublicKey({key:w,format:"jwk"}),L=P1.verify("sha256",h.Buffer.from(M),{key:D,dsaEncoding:"ieee-p1363"},u);if(!L&&t.allowLegacyDER)try{L=P1.verify("sha256",h.Buffer.from(M),{key:D,dsaEncoding:"der"},u)}catch{L=!1}return L?{valid:!0,header:a,payload:s}:{valid:!1,error:"Invalid signature",header:a,payload:s}}catch(U){return{valid:!1,error:U.message||"Verification failed"}}}dD.exports={issueVcJwt:koe,verifyVcJwt:Roe,base64UrlEncode:o5,base64UrlDecode:a5,ALG_TO_CRV:T1}});var gD=k((Bve,pD)=>{"use strict";v();function Boe(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}pD.exports=Boe});var k1=k(Ei=>{"use strict";v();var Moe=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function Noe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Ei.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var i in r)Noe(r,i)&&(e[i]=r[i])}}return e};Ei.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var Coe={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+i),n);return}for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){var t,r,i,n,o,a;for(i=0,t=0,r=e.length;t<r;t++)i+=e[t].length;for(a=new Uint8Array(i),n=0,t=0,r=e.length;t<r;t++)o=e[t],a.set(o,n),n+=o.length;return a}},Doe={arraySet:function(e,t,r,i,n){for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){return[].concat.apply([],e)}};Ei.setTyped=function(e){e?(Ei.Buf8=Uint8Array,Ei.Buf16=Uint16Array,Ei.Buf32=Int32Array,Ei.assign(Ei,Coe)):(Ei.Buf8=Array,Ei.Buf16=Array,Ei.Buf32=Array,Ei.assign(Ei,Doe))};Ei.setTyped(Moe)});var qD=k(Ul=>{"use strict";v();var Loe=k1(),qoe=4,vD=0,mD=1,Uoe=2;function ql(e){for(var t=e.length;--t>=0;)e[t]=0}var Foe=0,xD=1,Hoe=2,joe=3,zoe=258,m7=29,D1=256,B1=D1+1+m7,Ll=30,y7=19,ED=2*B1+1,Pf=15,l7=16,Koe=7,b7=256,OD=16,ID=17,AD=18,g7=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],s5=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Voe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],PD=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Goe=512,Ja=new Array((B1+2)*2);ql(Ja);var R1=new Array(Ll*2);ql(R1);var M1=new Array(Goe);ql(M1);var N1=new Array(zoe-joe+1);ql(N1);var _7=new Array(m7);ql(_7);var u5=new Array(Ll);ql(u5);function h7(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}var TD,kD,RD;function d7(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function BD(e){return e<256?M1[e]:M1[256+(e>>>7)]}function C1(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Ci(e,t,r){e.bi_valid>l7-r?(e.bi_buf|=t<<e.bi_valid&65535,C1(e,e.bi_buf),e.bi_buf=t>>l7-e.bi_valid,e.bi_valid+=r-l7):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function Xo(e,t,r){Ci(e,r[t*2],r[t*2+1])}function MD(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function Zoe(e){e.bi_valid===16?(C1(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Woe(e,t){var r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,l,m,w,E,P,M=0;for(w=0;w<=Pf;w++)e.bl_count[w]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<ED;c++)l=e.heap[c],w=r[r[l*2+1]*2+1]+1,w>u&&(w=u,M++),r[l*2+1]=w,!(l>i)&&(e.bl_count[w]++,E=0,l>=s&&(E=a[l-s]),P=r[l*2],e.opt_len+=P*(w+E),o&&(e.static_len+=P*(n[l*2+1]+E)));if(M!==0){do{for(w=u-1;e.bl_count[w]===0;)w--;e.bl_count[w]--,e.bl_count[w+1]+=2,e.bl_count[u]--,M-=2}while(M>0);for(w=u;w!==0;w--)for(l=e.bl_count[w];l!==0;)m=e.heap[--c],!(m>i)&&(r[m*2+1]!==w&&(e.opt_len+=(w-r[m*2+1])*r[m*2],r[m*2+1]=w),l--)}}function ND(e,t,r){var i=new Array(Pf+1),n=0,o,a;for(o=1;o<=Pf;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=t;a++){var s=e[a*2+1];s!==0&&(e[a*2]=MD(i[s]++,s))}}function Yoe(){var e,t,r,i,n,o=new Array(Pf+1);for(r=0,i=0;i<m7-1;i++)for(_7[i]=r,e=0;e<1<<g7[i];e++)N1[r++]=i;for(N1[r-1]=i,n=0,i=0;i<16;i++)for(u5[i]=n,e=0;e<1<<s5[i];e++)M1[n++]=i;for(n>>=7;i<Ll;i++)for(u5[i]=n<<7,e=0;e<1<<s5[i]-7;e++)M1[256+n++]=i;for(t=0;t<=Pf;t++)o[t]=0;for(e=0;e<=143;)Ja[e*2+1]=8,e++,o[8]++;for(;e<=255;)Ja[e*2+1]=9,e++,o[9]++;for(;e<=279;)Ja[e*2+1]=7,e++,o[7]++;for(;e<=287;)Ja[e*2+1]=8,e++,o[8]++;for(ND(Ja,B1+1,o),e=0;e<Ll;e++)R1[e*2+1]=5,R1[e*2]=MD(e,5);TD=new h7(Ja,g7,D1+1,B1,Pf),kD=new h7(R1,s5,0,Ll,Pf),RD=new h7(new Array(0),Voe,0,y7,Koe)}function CD(e){var t;for(t=0;t<B1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Ll;t++)e.dyn_dtree[t*2]=0;for(t=0;t<y7;t++)e.bl_tree[t*2]=0;e.dyn_ltree[b7*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function DD(e){e.bi_valid>8?C1(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function $oe(e,t,r,i){DD(e),i&&(C1(e,r),C1(e,~r)),Loe.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function yD(e,t,r,i){var n=t*2,o=r*2;return e[n]<e[o]||e[n]===e[o]&&i[t]<=i[r]}function p7(e,t,r){for(var i=e.heap[r],n=r<<1;n<=e.heap_len&&(n<e.heap_len&&yD(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!yD(t,i,e.heap[n],e.depth));)e.heap[r]=e.heap[n],r=n,n<<=1;e.heap[r]=i}function bD(e,t,r){var i,n,o=0,a,s;if(e.last_lit!==0)do i=e.pending_buf[e.d_buf+o*2]<<8|e.pending_buf[e.d_buf+o*2+1],n=e.pending_buf[e.l_buf+o],o++,i===0?Xo(e,n,t):(a=N1[n],Xo(e,a+D1+1,t),s=g7[a],s!==0&&(n-=_7[a],Ci(e,n,s)),i--,a=BD(i),Xo(e,a,r),s=s5[a],s!==0&&(i-=u5[a],Ci(e,i,s)));while(o<e.last_lit);Xo(e,b7,t)}function v7(e,t){var r=t.dyn_tree,i=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.elems,a,s,u=-1,c;for(e.heap_len=0,e.heap_max=ED,a=0;a<o;a++)r[a*2]!==0?(e.heap[++e.heap_len]=u=a,e.depth[a]=0):r[a*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,n&&(e.static_len-=i[c*2+1]);for(t.max_code=u,a=e.heap_len>>1;a>=1;a--)p7(e,r,a);c=o;do a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],p7(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=s,r[c*2]=r[a*2]+r[s*2],e.depth[c]=(e.depth[a]>=e.depth[s]?e.depth[a]:e.depth[s])+1,r[a*2+1]=r[s*2+1]=c,e.heap[1]=c++,p7(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Woe(e,t),ND(r,u,e.bl_count)}function _D(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),t[(r+1)*2+1]=65535,i=0;i<=r;i++)o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)&&(s<c?e.bl_tree[o*2]+=s:o!==0?(o!==n&&e.bl_tree[o*2]++,e.bl_tree[OD*2]++):s<=10?e.bl_tree[ID*2]++:e.bl_tree[AD*2]++,s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4))}function wD(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),i=0;i<=r;i++)if(o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)){if(s<c)do Xo(e,o,e.bl_tree);while(--s!==0);else o!==0?(o!==n&&(Xo(e,o,e.bl_tree),s--),Xo(e,OD,e.bl_tree),Ci(e,s-3,2)):s<=10?(Xo(e,ID,e.bl_tree),Ci(e,s-3,3)):(Xo(e,AD,e.bl_tree),Ci(e,s-11,7));s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4)}}function Xoe(e){var t;for(_D(e,e.dyn_ltree,e.l_desc.max_code),_D(e,e.dyn_dtree,e.d_desc.max_code),v7(e,e.bl_desc),t=y7-1;t>=3&&e.bl_tree[PD[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Joe(e,t,r,i){var n;for(Ci(e,t-257,5),Ci(e,r-1,5),Ci(e,i-4,4),n=0;n<i;n++)Ci(e,e.bl_tree[PD[n]*2+1],3);wD(e,e.dyn_ltree,t-1),wD(e,e.dyn_dtree,r-1)}function Qoe(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return vD;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return mD;for(r=32;r<D1;r++)if(e.dyn_ltree[r*2]!==0)return mD;return vD}var SD=!1;function eae(e){SD||(Yoe(),SD=!0),e.l_desc=new d7(e.dyn_ltree,TD),e.d_desc=new d7(e.dyn_dtree,kD),e.bl_desc=new d7(e.bl_tree,RD),e.bi_buf=0,e.bi_valid=0,CD(e)}function LD(e,t,r,i){Ci(e,(Foe<<1)+(i?1:0),3),$oe(e,t,r,!0)}function tae(e){Ci(e,xD<<1,3),Xo(e,b7,Ja),Zoe(e)}function rae(e,t,r,i){var n,o,a=0;e.level>0?(e.strm.data_type===Uoe&&(e.strm.data_type=Qoe(e)),v7(e,e.l_desc),v7(e,e.d_desc),a=Xoe(e),n=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=n&&(n=o)):n=o=r+5,r+4<=n&&t!==-1?LD(e,t,r,i):e.strategy===qoe||o===n?(Ci(e,(xD<<1)+(i?1:0),3),bD(e,Ja,R1)):(Ci(e,(Hoe<<1)+(i?1:0),3),Joe(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),bD(e,e.dyn_ltree,e.dyn_dtree)),CD(e),i&&DD(e)}function iae(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(N1[r]+D1+1)*2]++,e.dyn_dtree[BD(t)*2]++),e.last_lit===e.lit_bufsize-1}Ul._tr_init=eae;Ul._tr_stored_block=LD;Ul._tr_flush_block=rae;Ul._tr_tally=iae;Ul._tr_align=tae});var w7=k((qve,UD)=>{"use strict";v();function nae(e,t,r,i){for(var n=e&65535|0,o=e>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do n=n+t[i++]|0,o=o+n|0;while(--a);n%=65521,o%=65521}return n|o<<16|0}UD.exports=nae});var S7=k((Fve,FD)=>{"use strict";v();function oae(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var aae=oae();function sae(e,t,r,i){var n=aae,o=i+r;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[(e^t[a])&255];return e^-1}FD.exports=sae});var jD=k((jve,HD)=>{"use strict";v();HD.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var XD=k(ea=>{"use strict";v();var Oi=k1(),En=qD(),GD=w7(),qs=S7(),uae=jD(),Bf=0,fae=1,cae=3,zs=4,zD=5,Qo=0,KD=1,On=-2,lae=-3,x7=-5,hae=-1,dae=1,f5=2,pae=3,gae=4,vae=0,mae=2,d5=8,yae=9,bae=15,_ae=8,wae=29,Sae=256,O7=Sae+1+wae,xae=30,Eae=19,Oae=2*O7+1,Iae=15,bt=3,Hs=258,so=Hs+bt+1,Aae=32,p5=42,I7=69,c5=73,l5=91,h5=103,Tf=113,q1=666,Ur=1,U1=2,kf=3,jl=4,Pae=3;function js(e,t){return e.msg=uae[t],t}function VD(e){return(e<<1)-(e>4?9:0)}function Fs(e){for(var t=e.length;--t>=0;)e[t]=0}function Us(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Oi.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function oi(e,t){En._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Us(e.strm)}function Pt(e,t){e.pending_buf[e.pending++]=t}function L1(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function Tae(e,t,r,i){var n=e.avail_in;return n>i&&(n=i),n===0?0:(e.avail_in-=n,Oi.arraySet(t,e.input,e.next_in,n,r),e.state.wrap===1?e.adler=GD(e.adler,t,n,r):e.state.wrap===2&&(e.adler=qs(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function ZD(e,t){var r=e.max_chain_length,i=e.strstart,n,o,a=e.prev_length,s=e.nice_match,u=e.strstart>e.w_size-so?e.strstart-(e.w_size-so):0,c=e.window,l=e.w_mask,m=e.prev,w=e.strstart+Hs,E=c[i+a-1],P=c[i+a];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(n=t,!(c[n+a]!==P||c[n+a-1]!==E||c[n]!==c[i]||c[++n]!==c[i+1])){i+=2,n++;do;while(c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&i<w);if(o=Hs-(w-i),i=w-Hs,o>a){if(e.match_start=t,a=o,o>=s)break;E=c[i+a-1],P=c[i+a]}}while((t=m[t&l])>u&&--r!==0);return a<=e.lookahead?a:e.lookahead}function Rf(e){var t=e.w_size,r,i,n,o,a;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-so)){Oi.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do n=e.head[--r],e.head[r]=n>=t?n-t:0;while(--i);i=t,r=i;do n=e.prev[--r],e.prev[r]=n>=t?n-t:0;while(--i);o+=t}if(e.strm.avail_in===0)break;if(i=Tae(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=bt)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+bt-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<bt)););}while(e.lookahead<so&&e.strm.avail_in!==0)}function kae(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Rf(e),e.lookahead===0&&t===Bf)return Ur;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((e.strstart===0||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,oi(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-so&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):(e.strstart>e.block_start&&(oi(e,!1),e.strm.avail_out===0),Ur)}function E7(e,t){for(var r,i;;){if(e.lookahead<so){if(Rf(e),e.lookahead<so&&t===Bf)return Ur;if(e.lookahead===0)break}if(r=0,e.lookahead>=bt&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-so&&(e.match_length=ZD(e,r)),e.match_length>=bt)if(i=En._tr_tally(e,e.strstart-e.match_start,e.match_length-bt),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=bt){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=e.strstart<bt-1?e.strstart:bt-1,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Fl(e,t){for(var r,i,n;;){if(e.lookahead<so){if(Rf(e),e.lookahead<so&&t===Bf)return Ur;if(e.lookahead===0)break}if(r=0,e.lookahead>=bt&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=bt-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-so&&(e.match_length=ZD(e,r),e.match_length<=5&&(e.strategy===dae||e.match_length===bt&&e.strstart-e.match_start>4096)&&(e.match_length=bt-1)),e.prev_length>=bt&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-bt,i=En._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-bt),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=n&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+bt-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=bt-1,e.strstart++,i&&(oi(e,!1),e.strm.avail_out===0))return Ur}else if(e.match_available){if(i=En._tr_tally(e,0,e.window[e.strstart-1]),i&&oi(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return Ur}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=En._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<bt-1?e.strstart:bt-1,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Rae(e,t){for(var r,i,n,o,a=e.window;;){if(e.lookahead<=Hs){if(Rf(e),e.lookahead<=Hs&&t===Bf)return Ur;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=bt&&e.strstart>0&&(n=e.strstart-1,i=a[n],i===a[++n]&&i===a[++n]&&i===a[++n])){o=e.strstart+Hs;do;while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);e.match_length=Hs-(o-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=bt?(r=En._tr_tally(e,1,e.match_length-bt),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Bae(e,t){for(var r;;){if(e.lookahead===0&&(Rf(e),e.lookahead===0)){if(t===Bf)return Ur;break}if(e.match_length=0,r=En._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(oi(e,!1),e.strm.avail_out===0))return Ur}return e.insert=0,t===zs?(oi(e,!0),e.strm.avail_out===0?kf:jl):e.last_lit&&(oi(e,!1),e.strm.avail_out===0)?Ur:U1}function Jo(e,t,r,i,n){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=i,this.func=n}var Hl;Hl=[new Jo(0,0,0,0,kae),new Jo(4,4,8,4,E7),new Jo(4,5,16,8,E7),new Jo(4,6,32,32,E7),new Jo(4,4,16,16,Fl),new Jo(8,16,32,32,Fl),new Jo(8,16,128,128,Fl),new Jo(8,32,128,256,Fl),new Jo(32,128,258,1024,Fl),new Jo(32,258,258,4096,Fl)];function Mae(e){e.window_size=2*e.w_size,Fs(e.head),e.max_lazy_match=Hl[e.level].max_lazy,e.good_match=Hl[e.level].good_length,e.nice_match=Hl[e.level].nice_length,e.max_chain_length=Hl[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=bt-1,e.match_available=0,e.ins_h=0}function Nae(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=d5,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Oi.Buf16(Oae*2),this.dyn_dtree=new Oi.Buf16((2*xae+1)*2),this.bl_tree=new Oi.Buf16((2*Eae+1)*2),Fs(this.dyn_ltree),Fs(this.dyn_dtree),Fs(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Oi.Buf16(Iae+1),this.heap=new Oi.Buf16(2*O7+1),Fs(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Oi.Buf16(2*O7+1),Fs(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function WD(e){var t;return!e||!e.state?js(e,On):(e.total_in=e.total_out=0,e.data_type=mae,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?p5:Tf,e.adler=t.wrap===2?0:1,t.last_flush=Bf,En._tr_init(t),Qo)}function YD(e){var t=WD(e);return t===Qo&&Mae(e.state),t}function Cae(e,t){return!e||!e.state||e.state.wrap!==2?On:(e.state.gzhead=t,Qo)}function $D(e,t,r,i,n,o){if(!e)return On;var a=1;if(t===hae&&(t=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>yae||r!==d5||i<8||i>15||t<0||t>9||o<0||o>gae)return js(e,On);i===8&&(i=9);var s=new Nae;return e.state=s,s.strm=e,s.wrap=a,s.gzhead=null,s.w_bits=i,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=n+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+bt-1)/bt),s.window=new Oi.Buf8(s.w_size*2),s.head=new Oi.Buf16(s.hash_size),s.prev=new Oi.Buf16(s.w_size),s.lit_bufsize=1<<n+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Oi.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=o,s.method=r,YD(e)}function Dae(e,t){return $D(e,t,d5,bae,_ae,vae)}function Lae(e,t){var r,i,n,o;if(!e||!e.state||t>zD||t<0)return e?js(e,On):On;if(i=e.state,!e.output||!e.input&&e.avail_in!==0||i.status===q1&&t!==zs)return js(e,e.avail_out===0?x7:On);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===p5)if(i.wrap===2)e.adler=0,Pt(i,31),Pt(i,139),Pt(i,8),i.gzhead?(Pt(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Pt(i,i.gzhead.time&255),Pt(i,i.gzhead.time>>8&255),Pt(i,i.gzhead.time>>16&255),Pt(i,i.gzhead.time>>24&255),Pt(i,i.level===9?2:i.strategy>=f5||i.level<2?4:0),Pt(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(Pt(i,i.gzhead.extra.length&255),Pt(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=qs(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=I7):(Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,0),Pt(i,i.level===9?2:i.strategy>=f5||i.level<2?4:0),Pt(i,Pae),i.status=Tf);else{var a=d5+(i.w_bits-8<<4)<<8,s=-1;i.strategy>=f5||i.level<2?s=0:i.level<6?s=1:i.level===6?s=2:s=3,a|=s<<6,i.strstart!==0&&(a|=Aae),a+=31-a%31,i.status=Tf,L1(i,a),i.strstart!==0&&(L1(i,e.adler>>>16),L1(i,e.adler&65535)),e.adler=1}if(i.status===I7)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size));)Pt(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=c5)}else i.status=c5;if(i.status===c5)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.name.length?o=i.gzhead.name.charCodeAt(i.gzindex++)&255:o=0,Pt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.gzindex=0,i.status=l5)}else i.status=l5;if(i.status===l5)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),Us(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.comment.length?o=i.gzhead.comment.charCodeAt(i.gzindex++)&255:o=0,Pt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=qs(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.status=h5)}else i.status=h5;if(i.status===h5&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&Us(e),i.pending+2<=i.pending_buf_size&&(Pt(i,e.adler&255),Pt(i,e.adler>>8&255),e.adler=0,i.status=Tf)):i.status=Tf),i.pending!==0){if(Us(e),e.avail_out===0)return i.last_flush=-1,Qo}else if(e.avail_in===0&&VD(t)<=VD(r)&&t!==zs)return js(e,x7);if(i.status===q1&&e.avail_in!==0)return js(e,x7);if(e.avail_in!==0||i.lookahead!==0||t!==Bf&&i.status!==q1){var u=i.strategy===f5?Bae(i,t):i.strategy===pae?Rae(i,t):Hl[i.level].func(i,t);if((u===kf||u===jl)&&(i.status=q1),u===Ur||u===kf)return e.avail_out===0&&(i.last_flush=-1),Qo;if(u===U1&&(t===fae?En._tr_align(i):t!==zD&&(En._tr_stored_block(i,0,0,!1),t===cae&&(Fs(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),Us(e),e.avail_out===0))return i.last_flush=-1,Qo}return t!==zs?Qo:i.wrap<=0?KD:(i.wrap===2?(Pt(i,e.adler&255),Pt(i,e.adler>>8&255),Pt(i,e.adler>>16&255),Pt(i,e.adler>>24&255),Pt(i,e.total_in&255),Pt(i,e.total_in>>8&255),Pt(i,e.total_in>>16&255),Pt(i,e.total_in>>24&255)):(L1(i,e.adler>>>16),L1(i,e.adler&65535)),Us(e),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?Qo:KD)}function qae(e){var t;return!e||!e.state?On:(t=e.state.status,t!==p5&&t!==I7&&t!==c5&&t!==l5&&t!==h5&&t!==Tf&&t!==q1?js(e,On):(e.state=null,t===Tf?js(e,lae):Qo))}function Uae(e,t){var r=t.length,i,n,o,a,s,u,c,l;if(!e||!e.state||(i=e.state,a=i.wrap,a===2||a===1&&i.status!==p5||i.lookahead))return On;for(a===1&&(e.adler=GD(e.adler,t,r,0)),i.wrap=0,r>=i.w_size&&(a===0&&(Fs(i.head),i.strstart=0,i.block_start=0,i.insert=0),l=new Oi.Buf8(i.w_size),Oi.arraySet(l,t,r-i.w_size,i.w_size,0),t=l,r=i.w_size),s=e.avail_in,u=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,Rf(i);i.lookahead>=bt;){n=i.strstart,o=i.lookahead-(bt-1);do i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+bt-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++;while(--o);i.strstart=n,i.lookahead=bt-1,Rf(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=bt-1,i.match_available=0,e.next_in=u,e.input=c,e.avail_in=s,i.wrap=a,Qo}ea.deflateInit=Dae;ea.deflateInit2=$D;ea.deflateReset=YD;ea.deflateResetKeep=WD;ea.deflateSetHeader=Cae;ea.deflate=Lae;ea.deflateEnd=qae;ea.deflateSetDictionary=Uae;ea.deflateInfo="pako deflate (from Nodeca project)"});var QD=k((Gve,JD)=>{"use strict";v();var g5=30,Fae=12;JD.exports=function(t,r){var i,n,o,a,s,u,c,l,m,w,E,P,M,D,L,U,K,N,C,F,H,z,G,B,g;i=t.state,n=t.next_in,B=t.input,o=n+(t.avail_in-5),a=t.next_out,g=t.output,s=a-(r-t.avail_out),u=a+(t.avail_out-257),c=i.dmax,l=i.wsize,m=i.whave,w=i.wnext,E=i.window,P=i.hold,M=i.bits,D=i.lencode,L=i.distcode,U=(1<<i.lenbits)-1,K=(1<<i.distbits)-1;e:do{M<15&&(P+=B[n++]<<M,M+=8,P+=B[n++]<<M,M+=8),N=D[P&U];t:for(;;){if(C=N>>>24,P>>>=C,M-=C,C=N>>>16&255,C===0)g[a++]=N&65535;else if(C&16){F=N&65535,C&=15,C&&(M<C&&(P+=B[n++]<<M,M+=8),F+=P&(1<<C)-1,P>>>=C,M-=C),M<15&&(P+=B[n++]<<M,M+=8,P+=B[n++]<<M,M+=8),N=L[P&K];r:for(;;){if(C=N>>>24,P>>>=C,M-=C,C=N>>>16&255,C&16){if(H=N&65535,C&=15,M<C&&(P+=B[n++]<<M,M+=8,M<C&&(P+=B[n++]<<M,M+=8)),H+=P&(1<<C)-1,H>c){t.msg="invalid distance too far back",i.mode=g5;break e}if(P>>>=C,M-=C,C=a-s,H>C){if(C=H-C,C>m&&i.sane){t.msg="invalid distance too far back",i.mode=g5;break e}if(z=0,G=E,w===0){if(z+=l-C,C<F){F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}}else if(w<C){if(z+=l+w-C,C-=w,C<F){F-=C;do g[a++]=E[z++];while(--C);if(z=0,w<F){C=w,F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}}}else if(z+=w-C,C<F){F-=C;do g[a++]=E[z++];while(--C);z=a-H,G=g}for(;F>2;)g[a++]=G[z++],g[a++]=G[z++],g[a++]=G[z++],F-=3;F&&(g[a++]=G[z++],F>1&&(g[a++]=G[z++]))}else{z=a-H;do g[a++]=g[z++],g[a++]=g[z++],g[a++]=g[z++],F-=3;while(F>2);F&&(g[a++]=g[z++],F>1&&(g[a++]=g[z++]))}}else if((C&64)===0){N=L[(N&65535)+(P&(1<<C)-1)];continue r}else{t.msg="invalid distance code",i.mode=g5;break e}break}}else if((C&64)===0){N=D[(N&65535)+(P&(1<<C)-1)];continue t}else if(C&32){i.mode=Fae;break e}else{t.msg="invalid literal/length code",i.mode=g5;break e}break}}while(n<o&&a<u);F=M>>3,n-=F,M-=F<<3,P&=(1<<M)-1,t.next_in=n,t.next_out=a,t.avail_in=n<o?5+(o-n):5-(n-o),t.avail_out=a<u?257+(u-a):257-(a-u),i.hold=P,i.bits=M}});var aL=k((Wve,oL)=>{"use strict";v();var eL=k1(),zl=15,tL=852,rL=592,iL=0,A7=1,nL=2,Hae=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],jae=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],zae=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Kae=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];oL.exports=function(t,r,i,n,o,a,s,u){var c=u.bits,l=0,m=0,w=0,E=0,P=0,M=0,D=0,L=0,U=0,K=0,N,C,F,H,z,G=null,B=0,g,O=new eL.Buf16(zl+1),y=new eL.Buf16(zl+1),f=null,d=0,_,x,b;for(l=0;l<=zl;l++)O[l]=0;for(m=0;m<n;m++)O[r[i+m]]++;for(P=c,E=zl;E>=1&&O[E]===0;E--);if(P>E&&(P=E),E===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,u.bits=1,0;for(w=1;w<E&&O[w]===0;w++);for(P<w&&(P=w),L=1,l=1;l<=zl;l++)if(L<<=1,L-=O[l],L<0)return-1;if(L>0&&(t===iL||E!==1))return-1;for(y[1]=0,l=1;l<zl;l++)y[l+1]=y[l]+O[l];for(m=0;m<n;m++)r[i+m]!==0&&(s[y[r[i+m]]++]=m);if(t===iL?(G=f=s,g=19):t===A7?(G=Hae,B-=257,f=jae,d-=257,g=256):(G=zae,f=Kae,g=-1),K=0,m=0,l=w,z=a,M=P,D=0,F=-1,U=1<<P,H=U-1,t===A7&&U>tL||t===nL&&U>rL)return 1;for(;;){_=l-D,s[m]<g?(x=0,b=s[m]):s[m]>g?(x=f[d+s[m]],b=G[B+s[m]]):(x=96,b=0),N=1<<l-D,C=1<<M,w=C;do C-=N,o[z+(K>>D)+C]=_<<24|x<<16|b|0;while(C!==0);for(N=1<<l-1;K&N;)N>>=1;if(N!==0?(K&=N-1,K+=N):K=0,m++,--O[l]===0){if(l===E)break;l=r[i+s[m]]}if(l>P&&(K&H)!==F){for(D===0&&(D=P),z+=w,M=l-D,L=1<<M;M+D<E&&(L-=O[M+D],!(L<=0));)M++,L<<=1;if(U+=1<<M,t===A7&&U>tL||t===nL&&U>rL)return 1;F=K&H,o[F]=P<<24|M<<16|z-a|0}}return K!==0&&(o[z+K]=l-D<<24|64<<16|0),u.bits=P,0}});var HL=k(uo=>{"use strict";v();var Wi=k1(),M7=w7(),ta=S7(),Vae=QD(),F1=aL(),Gae=0,BL=1,ML=2,sL=4,Zae=5,v5=6,Mf=0,Wae=1,Yae=2,In=-2,NL=-3,N7=-4,$ae=-5,uL=8,CL=1,fL=2,cL=3,lL=4,hL=5,dL=6,pL=7,gL=8,vL=9,mL=10,b5=11,Qa=12,P7=13,yL=14,T7=15,bL=16,_L=17,wL=18,SL=19,m5=20,y5=21,xL=22,EL=23,OL=24,IL=25,AL=26,k7=27,PL=28,TL=29,rr=30,C7=31,Xae=32,Jae=852,Qae=592,ese=15,tse=ese;function kL(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function rse(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Wi.Buf16(320),this.work=new Wi.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function DL(e){var t;return!e||!e.state?In:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=CL,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Wi.Buf32(Jae),t.distcode=t.distdyn=new Wi.Buf32(Qae),t.sane=1,t.back=-1,Mf)}function LL(e){var t;return!e||!e.state?In:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,DL(e))}function qL(e,t){var r,i;return!e||!e.state||(i=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?In:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,LL(e))}function UL(e,t){var r,i;return e?(i=new rse,e.state=i,i.window=null,r=qL(e,t),r!==Mf&&(e.state=null),r):In}function ise(e){return UL(e,tse)}var RL=!0,R7,B7;function nse(e){if(RL){var t;for(R7=new Wi.Buf32(512),B7=new Wi.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(F1(BL,e.lens,0,288,R7,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;F1(ML,e.lens,0,32,B7,0,e.work,{bits:5}),RL=!1}e.lencode=R7,e.lenbits=9,e.distcode=B7,e.distbits=5}function FL(e,t,r,i){var n,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Wi.Buf8(o.wsize)),i>=o.wsize?(Wi.arraySet(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),Wi.arraySet(o.window,t,r-i,n,o.wnext),i-=n,i?(Wi.arraySet(o.window,t,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function ose(e,t){var r,i,n,o,a,s,u,c,l,m,w,E,P,M,D=0,L,U,K,N,C,F,H,z,G=new Wi.Buf8(4),B,g,O=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return In;r=e.state,r.mode===Qa&&(r.mode=P7),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,m=s,w=u,z=Mf;e:for(;;)switch(r.mode){case CL:if(r.wrap===0){r.mode=P7;break}for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.wrap&2&&c===35615){r.check=0,G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0),c=0,l=0,r.mode=fL;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=rr;break}if((c&15)!==uL){e.msg="unknown compression method",r.mode=rr;break}if(c>>>=4,l-=4,H=(c&15)+8,r.wbits===0)r.wbits=H;else if(H>r.wbits){e.msg="invalid window size",r.mode=rr;break}r.dmax=1<<H,e.adler=r.check=1,r.mode=c&512?mL:Qa,c=0,l=0;break;case fL:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.flags=c,(r.flags&255)!==uL){e.msg="unknown compression method",r.mode=rr;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=rr;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0,r.mode=cL;case cL:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.time=c),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,G[2]=c>>>16&255,G[3]=c>>>24&255,r.check=ta(r.check,G,4,0)),c=0,l=0,r.mode=lL;case lL:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0,r.mode=hL;case hL:if(r.flags&1024){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(G[0]=c&255,G[1]=c>>>8&255,r.check=ta(r.check,G,2,0)),c=0,l=0}else r.head&&(r.head.extra=null);r.mode=dL;case dL:if(r.flags&1024&&(E=r.length,E>s&&(E=s),E&&(r.head&&(H=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Wi.arraySet(r.head.extra,i,o,E,H)),r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,r.length-=E),r.length))break e;r.length=0,r.mode=pL;case pL:if(r.flags&2048){if(s===0)break e;E=0;do H=i[o+E++],r.head&&H&&r.length<65536&&(r.head.name+=String.fromCharCode(H));while(H&&E<s);if(r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,H)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=gL;case gL:if(r.flags&4096){if(s===0)break e;E=0;do H=i[o+E++],r.head&&H&&r.length<65536&&(r.head.comment+=String.fromCharCode(H));while(H&&E<s);if(r.flags&512&&(r.check=ta(r.check,i,E,o)),s-=E,o+=E,H)break e}else r.head&&(r.head.comment=null);r.mode=vL;case vL:if(r.flags&512){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=rr;break}c=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Qa;break;case mL:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}e.adler=r.check=kL(c),c=0,l=0,r.mode=b5;case b5:if(r.havedict===0)return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,Yae;e.adler=r.check=1,r.mode=Qa;case Qa:if(t===Zae||t===v5)break e;case P7:if(r.last){c>>>=l&7,l-=l&7,r.mode=k7;break}for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}switch(r.last=c&1,c>>>=1,l-=1,c&3){case 0:r.mode=yL;break;case 1:if(nse(r),r.mode=m5,t===v5){c>>>=2,l-=2;break e}break;case 2:r.mode=_L;break;case 3:e.msg="invalid block type",r.mode=rr}c>>>=2,l-=2;break;case yL:for(c>>>=l&7,l-=l&7;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=rr;break}if(r.length=c&65535,c=0,l=0,r.mode=T7,t===v5)break e;case T7:r.mode=bL;case bL:if(E=r.length,E){if(E>s&&(E=s),E>u&&(E=u),E===0)break e;Wi.arraySet(n,i,o,E,a),s-=E,o+=E,u-=E,a+=E,r.length-=E;break}r.mode=Qa;break;case _L:for(;l<14;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.nlen=(c&31)+257,c>>>=5,l-=5,r.ndist=(c&31)+1,c>>>=5,l-=5,r.ncode=(c&15)+4,c>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=rr;break}r.have=0,r.mode=wL;case wL:for(;r.have<r.ncode;){for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.lens[O[r.have++]]=c&7,c>>>=3,l-=3}for(;r.have<19;)r.lens[O[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,B={bits:r.lenbits},z=F1(Gae,r.lens,0,19,r.lencode,0,r.work,B),r.lenbits=B.bits,z){e.msg="invalid code lengths set",r.mode=rr;break}r.have=0,r.mode=SL;case SL:for(;r.have<r.nlen+r.ndist;){for(;D=r.lencode[c&(1<<r.lenbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(K<16)c>>>=L,l-=L,r.lens[r.have++]=K;else{if(K===16){for(g=L+2;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c>>>=L,l-=L,r.have===0){e.msg="invalid bit length repeat",r.mode=rr;break}H=r.lens[r.have-1],E=3+(c&3),c>>>=2,l-=2}else if(K===17){for(g=L+3;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=L,l-=L,H=0,E=3+(c&7),c>>>=3,l-=3}else{for(g=L+7;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=L,l-=L,H=0,E=11+(c&127),c>>>=7,l-=7}if(r.have+E>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=rr;break}for(;E--;)r.lens[r.have++]=H}}if(r.mode===rr)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=rr;break}if(r.lenbits=9,B={bits:r.lenbits},z=F1(BL,r.lens,0,r.nlen,r.lencode,0,r.work,B),r.lenbits=B.bits,z){e.msg="invalid literal/lengths set",r.mode=rr;break}if(r.distbits=6,r.distcode=r.distdyn,B={bits:r.distbits},z=F1(ML,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,B),r.distbits=B.bits,z){e.msg="invalid distances set",r.mode=rr;break}if(r.mode=m5,t===v5)break e;case m5:r.mode=y5;case y5:if(s>=6&&u>=258){e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,Vae(e,w),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,r.mode===Qa&&(r.back=-1);break}for(r.back=0;D=r.lencode[c&(1<<r.lenbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(U&&(U&240)===0){for(N=L,C=U,F=K;D=r.lencode[F+((c&(1<<N+C)-1)>>N)],L=D>>>24,U=D>>>16&255,K=D&65535,!(N+L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=N,l-=N,r.back+=N}if(c>>>=L,l-=L,r.back+=L,r.length=K,U===0){r.mode=AL;break}if(U&32){r.back=-1,r.mode=Qa;break}if(U&64){e.msg="invalid literal/length code",r.mode=rr;break}r.extra=U&15,r.mode=xL;case xL:if(r.extra){for(g=r.extra;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=EL;case EL:for(;D=r.distcode[c&(1<<r.distbits)-1],L=D>>>24,U=D>>>16&255,K=D&65535,!(L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((U&240)===0){for(N=L,C=U,F=K;D=r.distcode[F+((c&(1<<N+C)-1)>>N)],L=D>>>24,U=D>>>16&255,K=D&65535,!(N+L<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=N,l-=N,r.back+=N}if(c>>>=L,l-=L,r.back+=L,U&64){e.msg="invalid distance code",r.mode=rr;break}r.offset=K,r.extra=U&15,r.mode=OL;case OL:if(r.extra){for(g=r.extra;l<g;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=rr;break}r.mode=IL;case IL:if(u===0)break e;if(E=w-u,r.offset>E){if(E=r.offset-E,E>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=rr;break}E>r.wnext?(E-=r.wnext,P=r.wsize-E):P=r.wnext-E,E>r.length&&(E=r.length),M=r.window}else M=n,P=a-r.offset,E=r.length;E>u&&(E=u),u-=E,r.length-=E;do n[a++]=M[P++];while(--E);r.length===0&&(r.mode=y5);break;case AL:if(u===0)break e;n[a++]=r.length,u--,r.mode=y5;break;case k7:if(r.wrap){for(;l<32;){if(s===0)break e;s--,c|=i[o++]<<l,l+=8}if(w-=u,e.total_out+=w,r.total+=w,w&&(e.adler=r.check=r.flags?ta(r.check,n,w,a-w):M7(r.check,n,w,a-w)),w=u,(r.flags?c:kL(c))!==r.check){e.msg="incorrect data check",r.mode=rr;break}c=0,l=0}r.mode=PL;case PL:if(r.wrap&&r.flags){for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=rr;break}c=0,l=0}r.mode=TL;case TL:z=Wae;break e;case rr:z=NL;break e;case C7:return N7;case Xae:default:return In}return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,(r.wsize||w!==e.avail_out&&r.mode<rr&&(r.mode<k7||t!==sL))&&FL(e,e.output,e.next_out,w-e.avail_out)?(r.mode=C7,N7):(m-=e.avail_in,w-=e.avail_out,e.total_in+=m,e.total_out+=w,r.total+=w,r.wrap&&w&&(e.adler=r.check=r.flags?ta(r.check,n,w,e.next_out-w):M7(r.check,n,w,e.next_out-w)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Qa?128:0)+(r.mode===m5||r.mode===T7?256:0),(m===0&&w===0||t===sL)&&z===Mf&&(z=$ae),z)}function ase(e){if(!e||!e.state)return In;var t=e.state;return t.window&&(t.window=null),e.state=null,Mf}function sse(e,t){var r;return!e||!e.state||(r=e.state,(r.wrap&2)===0)?In:(r.head=t,t.done=!1,Mf)}function use(e,t){var r=t.length,i,n,o;return!e||!e.state||(i=e.state,i.wrap!==0&&i.mode!==b5)?In:i.mode===b5&&(n=1,n=M7(n,t,r,0),n!==i.check)?NL:(o=FL(e,t,r,r),o?(i.mode=C7,N7):(i.havedict=1,Mf))}uo.inflateReset=LL;uo.inflateReset2=qL;uo.inflateResetKeep=DL;uo.inflateInit=ise;uo.inflateInit2=UL;uo.inflate=ose;uo.inflateEnd=ase;uo.inflateGetHeader=sse;uo.inflateSetDictionary=use;uo.inflateInfo="pako inflate (from Nodeca project)"});var zL=k((Jve,jL)=>{"use strict";v();jL.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var VL=k(de=>{"use strict";v();var Yi=Es(),fse=gD(),H1=XD(),Nf=HL(),KL=zL();for(D7 in KL)de[D7]=KL[D7];var D7;de.NONE=0;de.DEFLATE=1;de.INFLATE=2;de.GZIP=3;de.GUNZIP=4;de.DEFLATERAW=5;de.INFLATERAW=6;de.UNZIP=7;var cse=31,lse=139;function mi(e){if(typeof e!="number"||e<de.DEFLATE||e>de.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}mi.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,Yi(this.init_done,"close before init"),Yi(this.mode<=de.UNZIP),this.mode===de.DEFLATE||this.mode===de.GZIP||this.mode===de.DEFLATERAW?H1.deflateEnd(this.strm):(this.mode===de.INFLATE||this.mode===de.GUNZIP||this.mode===de.INFLATERAW||this.mode===de.UNZIP)&&Nf.inflateEnd(this.strm),this.mode=de.NONE,this.dictionary=null};mi.prototype.write=function(e,t,r,i,n,o,a){return this._write(!0,e,t,r,i,n,o,a)};mi.prototype.writeSync=function(e,t,r,i,n,o,a){return this._write(!1,e,t,r,i,n,o,a)};mi.prototype._write=function(e,t,r,i,n,o,a,s){if(Yi.equal(arguments.length,8),Yi(this.init_done,"write before init"),Yi(this.mode!==de.NONE,"already finalized"),Yi.equal(!1,this.write_in_progress,"write already in progress"),Yi.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,Yi.equal(!1,t===void 0,"must provide flush value"),this.write_in_progress=!0,t!==de.Z_NO_FLUSH&&t!==de.Z_PARTIAL_FLUSH&&t!==de.Z_SYNC_FLUSH&&t!==de.Z_FULL_FLUSH&&t!==de.Z_FINISH&&t!==de.Z_BLOCK)throw new Error("Invalid flush value");if(r==null&&(r=h.Buffer.alloc(0),n=0,i=0),this.strm.avail_in=n,this.strm.input=r,this.strm.next_in=i,this.strm.avail_out=s,this.strm.output=o,this.strm.next_out=a,this.flush=t,!e)return this._process(),this._checkError()?this._afterSync():void 0;var u=this;return A.default.nextTick(function(){u._process(),u._after()}),this};mi.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]};mi.prototype._process=function(){var e=null;switch(this.mode){case de.DEFLATE:case de.GZIP:case de.DEFLATERAW:this.err=H1.deflate(this.strm,this.flush);break;case de.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(e===null)break;if(this.strm.input[e]===cse){if(this.gzip_id_bytes_read=1,e++,this.strm.avail_in===1)break}else{this.mode=de.INFLATE;break}case 1:if(e===null)break;this.strm.input[e]===lse?(this.gzip_id_bytes_read=2,this.mode=de.GUNZIP):this.mode=de.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case de.INFLATE:case de.GUNZIP:case de.INFLATERAW:for(this.err=Nf.inflate(this.strm,this.flush),this.err===de.Z_NEED_DICT&&this.dictionary&&(this.err=Nf.inflateSetDictionary(this.strm,this.dictionary),this.err===de.Z_OK?this.err=Nf.inflate(this.strm,this.flush):this.err===de.Z_DATA_ERROR&&(this.err=de.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===de.GUNZIP&&this.err===de.Z_STREAM_END&&this.strm.next_in[0]!==0;)this.reset(),this.err=Nf.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}};mi.prototype._checkError=function(){switch(this.err){case de.Z_OK:case de.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===de.Z_FINISH)return this._error("unexpected end of file"),!1;break;case de.Z_STREAM_END:break;case de.Z_NEED_DICT:return this.dictionary==null?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0};mi.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}};mi.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()};mi.prototype.init=function(e,t,r,i,n){Yi(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),Yi(e>=8&&e<=15,"invalid windowBits"),Yi(t>=-1&&t<=9,"invalid compression level"),Yi(r>=1&&r<=9,"invalid memlevel"),Yi(i===de.Z_FILTERED||i===de.Z_HUFFMAN_ONLY||i===de.Z_RLE||i===de.Z_FIXED||i===de.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(t,e,r,i,n),this._setDictionary()};mi.prototype.params=function(){throw new Error("deflateParams Not supported")};mi.prototype.reset=function(){this._reset(),this._setDictionary()};mi.prototype._init=function(e,t,r,i,n){switch(this.level=e,this.windowBits=t,this.memLevel=r,this.strategy=i,this.flush=de.Z_NO_FLUSH,this.err=de.Z_OK,(this.mode===de.GZIP||this.mode===de.GUNZIP)&&(this.windowBits+=16),this.mode===de.UNZIP&&(this.windowBits+=32),(this.mode===de.DEFLATERAW||this.mode===de.INFLATERAW)&&(this.windowBits=-1*this.windowBits),this.strm=new fse,this.mode){case de.DEFLATE:case de.GZIP:case de.DEFLATERAW:this.err=H1.deflateInit2(this.strm,this.level,de.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case de.INFLATE:case de.GUNZIP:case de.INFLATERAW:case de.UNZIP:this.err=Nf.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==de.Z_OK&&this._error("Init error"),this.dictionary=n,this.write_in_progress=!1,this.init_done=!0};mi.prototype._setDictionary=function(){if(this.dictionary!=null){switch(this.err=de.Z_OK,this.mode){case de.DEFLATE:case de.DEFLATERAW:this.err=H1.deflateSetDictionary(this.strm,this.dictionary);break;default:break}this.err!==de.Z_OK&&this._error("Failed to set dictionary")}};mi.prototype._reset=function(){switch(this.err=de.Z_OK,this.mode){case de.DEFLATE:case de.DEFLATERAW:case de.GZIP:this.err=H1.deflateReset(this.strm);break;case de.INFLATE:case de.INFLATERAW:case de.GUNZIP:this.err=Nf.inflateReset(this.strm);break;default:break}this.err!==de.Z_OK&&this._error("Failed to reset stream")};de.Zlib=mi});var U7=k(we=>{"use strict";v();var ra=Kt().Buffer,YL=t2().Transform,De=VL(),Ks=rn(),j1=Es().ok,q7=Kt().kMaxLength,$L="Cannot create final Buffer. It would be larger than 0x"+q7.toString(16)+" bytes";De.Z_MIN_WINDOWBITS=8;De.Z_MAX_WINDOWBITS=15;De.Z_DEFAULT_WINDOWBITS=15;De.Z_MIN_CHUNK=64;De.Z_MAX_CHUNK=1/0;De.Z_DEFAULT_CHUNK=16*1024;De.Z_MIN_MEMLEVEL=1;De.Z_MAX_MEMLEVEL=9;De.Z_DEFAULT_MEMLEVEL=8;De.Z_MIN_LEVEL=-1;De.Z_MAX_LEVEL=9;De.Z_DEFAULT_LEVEL=De.Z_DEFAULT_COMPRESSION;var GL=Object.keys(De);for(_5=0;_5<GL.length;_5++)w5=GL[_5],w5.match(/^Z/)&&Object.defineProperty(we,w5,{enumerable:!0,value:De[w5],writable:!1});var w5,_5,x5={Z_OK:De.Z_OK,Z_STREAM_END:De.Z_STREAM_END,Z_NEED_DICT:De.Z_NEED_DICT,Z_ERRNO:De.Z_ERRNO,Z_STREAM_ERROR:De.Z_STREAM_ERROR,Z_DATA_ERROR:De.Z_DATA_ERROR,Z_MEM_ERROR:De.Z_MEM_ERROR,Z_BUF_ERROR:De.Z_BUF_ERROR,Z_VERSION_ERROR:De.Z_VERSION_ERROR},ZL=Object.keys(x5);for(S5=0;S5<ZL.length;S5++)L7=ZL[S5],x5[x5[L7]]=L7;var L7,S5;Object.defineProperty(we,"codes",{enumerable:!0,value:Object.freeze(x5),writable:!1});we.Deflate=Cf;we.Inflate=Df;we.Gzip=Lf;we.Gunzip=qf;we.DeflateRaw=Uf;we.InflateRaw=Ff;we.Unzip=Hf;we.createDeflate=function(e){return new Cf(e)};we.createInflate=function(e){return new Df(e)};we.createDeflateRaw=function(e){return new Uf(e)};we.createInflateRaw=function(e){return new Ff(e)};we.createGzip=function(e){return new Lf(e)};we.createGunzip=function(e){return new qf(e)};we.createUnzip=function(e){return new Hf(e)};we.deflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Cf(t),e,r)};we.deflateSync=function(e,t){return zf(new Cf(t),e)};we.gzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Lf(t),e,r)};we.gzipSync=function(e,t){return zf(new Lf(t),e)};we.deflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Uf(t),e,r)};we.deflateRawSync=function(e,t){return zf(new Uf(t),e)};we.unzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Hf(t),e,r)};we.unzipSync=function(e,t){return zf(new Hf(t),e)};we.inflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Df(t),e,r)};we.inflateSync=function(e,t){return zf(new Df(t),e)};we.gunzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new qf(t),e,r)};we.gunzipSync=function(e,t){return zf(new qf(t),e)};we.inflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),jf(new Ff(t),e,r)};we.inflateRawSync=function(e,t){return zf(new Ff(t),e)};function jf(e,t,r){var i=[],n=0;e.on("error",a),e.on("end",s),e.end(t),o();function o(){for(var u;(u=e.read())!==null;)i.push(u),n+=u.length;e.once("readable",o)}function a(u){e.removeListener("end",s),e.removeListener("readable",o),r(u)}function s(){var u,c=null;n>=q7?c=new RangeError($L):u=ra.concat(i,n),i=[],e.close(),r(c,u)}}function zf(e,t){if(typeof t=="string"&&(t=ra.from(t)),!ra.isBuffer(t))throw new TypeError("Not a string or buffer");var r=e._finishFlushFlag;return e._processChunk(t,r)}function Cf(e){if(!(this instanceof Cf))return new Cf(e);hr.call(this,e,De.DEFLATE)}function Df(e){if(!(this instanceof Df))return new Df(e);hr.call(this,e,De.INFLATE)}function Lf(e){if(!(this instanceof Lf))return new Lf(e);hr.call(this,e,De.GZIP)}function qf(e){if(!(this instanceof qf))return new qf(e);hr.call(this,e,De.GUNZIP)}function Uf(e){if(!(this instanceof Uf))return new Uf(e);hr.call(this,e,De.DEFLATERAW)}function Ff(e){if(!(this instanceof Ff))return new Ff(e);hr.call(this,e,De.INFLATERAW)}function Hf(e){if(!(this instanceof Hf))return new Hf(e);hr.call(this,e,De.UNZIP)}function WL(e){return e===De.Z_NO_FLUSH||e===De.Z_PARTIAL_FLUSH||e===De.Z_SYNC_FLUSH||e===De.Z_FULL_FLUSH||e===De.Z_FINISH||e===De.Z_BLOCK}function hr(e,t){var r=this;if(this._opts=e=e||{},this._chunkSize=e.chunkSize||we.Z_DEFAULT_CHUNK,YL.call(this,e),e.flush&&!WL(e.flush))throw new Error("Invalid flush flag: "+e.flush);if(e.finishFlush&&!WL(e.finishFlush))throw new Error("Invalid flush flag: "+e.finishFlush);if(this._flushFlag=e.flush||De.Z_NO_FLUSH,this._finishFlushFlag=typeof e.finishFlush<"u"?e.finishFlush:De.Z_FINISH,e.chunkSize&&(e.chunkSize<we.Z_MIN_CHUNK||e.chunkSize>we.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<we.Z_MIN_WINDOWBITS||e.windowBits>we.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<we.Z_MIN_LEVEL||e.level>we.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<we.Z_MIN_MEMLEVEL||e.memLevel>we.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=we.Z_FILTERED&&e.strategy!=we.Z_HUFFMAN_ONLY&&e.strategy!=we.Z_RLE&&e.strategy!=we.Z_FIXED&&e.strategy!=we.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!ra.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new De.Zlib(t);var i=this;this._hadError=!1,this._handle.onerror=function(a,s){E5(i),i._hadError=!0;var u=new Error(a);u.errno=s,u.code=we.codes[s],i.emit("error",u)};var n=we.Z_DEFAULT_COMPRESSION;typeof e.level=="number"&&(n=e.level);var o=we.Z_DEFAULT_STRATEGY;typeof e.strategy=="number"&&(o=e.strategy),this._handle.init(e.windowBits||we.Z_DEFAULT_WINDOWBITS,n,e.memLevel||we.Z_DEFAULT_MEMLEVEL,o,e.dictionary),this._buffer=ra.allocUnsafe(this._chunkSize),this._offset=0,this._level=n,this._strategy=o,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!r._handle},configurable:!0,enumerable:!0})}Ks.inherits(hr,YL);hr.prototype.params=function(e,t,r){if(e<we.Z_MIN_LEVEL||e>we.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=we.Z_FILTERED&&t!=we.Z_HUFFMAN_ONLY&&t!=we.Z_RLE&&t!=we.Z_FIXED&&t!=we.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var i=this;this.flush(De.Z_SYNC_FLUSH,function(){j1(i._handle,"zlib binding closed"),i._handle.params(e,t),i._hadError||(i._level=e,i._strategy=t,r&&r())})}else A.default.nextTick(r)};hr.prototype.reset=function(){return j1(this._handle,"zlib binding closed"),this._handle.reset()};hr.prototype._flush=function(e){this._transform(ra.alloc(0),"",e)};hr.prototype.flush=function(e,t){var r=this,i=this._writableState;(typeof e=="function"||e===void 0&&!t)&&(t=e,e=De.Z_FULL_FLUSH),i.ended?t&&A.default.nextTick(t):i.ending?t&&this.once("end",t):i.needDrain?t&&this.once("drain",function(){return r.flush(e,t)}):(this._flushFlag=e,this.write(ra.alloc(0),"",t))};hr.prototype.close=function(e){E5(this,e),A.default.nextTick(hse,this)};function E5(e,t){t&&A.default.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}function hse(e){e.emit("close")}hr.prototype._transform=function(e,t,r){var i,n=this._writableState,o=n.ending||n.ended,a=o&&(!e||n.length===e.length);if(e!==null&&!ra.isBuffer(e))return r(new Error("invalid input"));if(!this._handle)return r(new Error("zlib binding closed"));a?i=this._finishFlushFlag:(i=this._flushFlag,e.length>=n.length&&(this._flushFlag=this._opts.flush||De.Z_NO_FLUSH)),this._processChunk(e,i,r)};hr.prototype._processChunk=function(e,t,r){var i=e&&e.length,n=this._chunkSize-this._offset,o=0,a=this,s=typeof r=="function";if(!s){var u=[],c=0,l;this.on("error",function(M){l=M}),j1(this._handle,"zlib binding closed");do var m=this._handle.writeSync(t,e,o,i,this._buffer,this._offset,n);while(!this._hadError&&P(m[0],m[1]));if(this._hadError)throw l;if(c>=q7)throw E5(this),new RangeError($L);var w=ra.concat(u,c);return E5(this),w}j1(this._handle,"zlib binding closed");var E=this._handle.write(t,e,o,i,this._buffer,this._offset,n);E.buffer=e,E.callback=P;function P(M,D){if(this&&(this.buffer=null,this.callback=null),!a._hadError){var L=n-D;if(j1(L>=0,"have should not go down"),L>0){var U=a._buffer.slice(a._offset,a._offset+L);a._offset+=L,s?a.push(U):(u.push(U),c+=U.length)}if((D===0||a._offset>=a._chunkSize)&&(n=a._chunkSize,a._offset=0,a._buffer=ra.allocUnsafe(a._chunkSize)),D===0){if(o+=i-M,i=M,!s)return!0;var K=a._handle.write(t,e,o,i,a._buffer,a._offset,a._chunkSize);K.callback=P,K.buffer=e;return}if(!s)return!1;r()}}};Ks.inherits(Cf,hr);Ks.inherits(Df,hr);Ks.inherits(Lf,hr);Ks.inherits(qf,hr);Ks.inherits(Uf,hr);Ks.inherits(Ff,hr);Ks.inherits(Hf,hr)});var tq=k((ome,eq)=>{"use strict";v();var F7=c7(),nme=_r(),XL=U7(),dse=8*1024*1024;function JL(e,t){var r=t&&t.maxDecompressedBytes||dse;return XL.gunzipSync(h.Buffer.from(e,"base64"),{maxOutputLength:r})}async function QL(e,t){if(!t.expectedIssuerDid)throw new Error("expectedIssuerDid is required to verify a status list (issuer pinning); refusing to read revocation state from an unpinned/unverified JWT");var r=t.didResolver;if(!r){var i=t.issuerJwks||(t.issuerPublicJwk?{keys:[t.issuerPublicJwk]}:null);if(!i)throw new Error("Provide params.didResolver, params.issuerJwks, or params.issuerPublicJwk to verify the status list signature");r=async function(){return{jwks:i}}}var n=await F7.verifyVcJwt(e,{didResolver:r,expectedIssuerDid:t.expectedIssuerDid,allowedAlgs:t.allowedAlgs,allowLegacyDER:t.allowLegacyDER,clockToleranceSec:t.clockToleranceSec});if(!n.valid)throw new Error("Status list signature verification failed: "+(n.error||"invalid signature"));return n.payload}async function pse(e){if(!e.issuerDid||!e.privateJwk)throw new Error("issuerDid and privateJwk are required");var t=e.listId||e.issuerDid+"/status/"+Date.now(),r=e.listSize||1e5,i=Math.ceil(r/8),n=h.Buffer.alloc(i,0),o=U7(),a=o.gzipSync(n),s=a.toString("base64"),u={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],type:["VerifiableCredential","StatusList2021Credential"],issuer:e.issuerDid,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,type:"StatusList2021",statusPurpose:"revocation",encodedList:s}},c=await F7.issueVcJwt({issuerDid:e.issuerDid,subjectId:t,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:u.credentialSubject,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:c.jwt,listId:t}}async function gse(e){if(!e.listVcJwt||e.index===void 0||!e.status||!e.privateJwk)throw new Error("listVcJwt, index, status, and privateJwk are required");if(e.status==="suspended")throw new Error("status 'suspended' is not supported by this list: its statusPurpose is 'revocation', and suspension would be written to the same bit and read back as 'revoked'. Maintain a separate list for suspension until statusPurpose is configurable.");var t=await QL(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=JL(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=e.status==="revoked"?1:0;a===1?i[n]|=1<<o:i[n]&=~(1<<o);var s=XL.gzipSync(i),u=s.toString("base64"),c={id:t.vc.credentialSubject.id,type:"StatusList2021",statusPurpose:"revocation",encodedList:u},l=await F7.issueVcJwt({issuerDid:t.iss,subjectId:t.vc.credentialSubject.id,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:c,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:l.jwt}}async function vse(e){if(!e.listVcJwt||e.index===void 0)throw new Error("listVcJwt and index are required");var t=await QL(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=JL(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=i[n]>>o&1;return a===1?"revoked":"valid"}eq.exports={createStatusList:pse,updateStatusList:gse,getCredentialStatusEntry:vse}});var nq=k((sme,iq)=>{"use strict";v();var mse=_r();function rq(e){var t;if(typeof e=="string")t=h.Buffer.from(e,"utf8");else if(h.Buffer.isBuffer(e))t=e;else if(e instanceof Uint8Array)t=h.Buffer.from(e);else throw new Error("Data must be string, Buffer, or Uint8Array");return mse.createHash("sha256").update(t).digest("hex")}function yse(e){if(!e.kind||!e.hash||!e.issuerDid)throw new Error("kind, hash, and issuerDid are required");var t=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];if(t.indexOf(e.kind)===-1)throw new Error("Invalid kind. Must be one of: "+t.join(", "));if(!/^[a-fA-F0-9]{64}$/.test(e.hash))throw new Error("Invalid hash format. Must be 64 hex characters");var r={protocol:"SmartLedger",version:"1.0",type:e.kind,hash:e.hash,issuer:e.issuerDid,timestamp:e.issuedAt||new Date().toISOString()};return{json:JSON.stringify(r)}}function bse(e,t){var r=rq(e);return r===t}function _se(e){try{var t=JSON.parse(e);if(t.protocol!=="SmartLedger")return{valid:!1,error:"Invalid protocol"};var r=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];return r.indexOf(t.type)===-1?{valid:!1,error:"Invalid anchor type"}:/^[a-fA-F0-9]{64}$/.test(t.hash)?{valid:!0,protocol:t.protocol,version:t.version,type:t.type,hash:t.hash,issuer:t.issuer,timestamp:t.timestamp}:{valid:!1,error:"Invalid hash format"}}catch(i){return{valid:!1,error:"Failed to parse anchor payload: "+i.message}}}iq.exports={sha256Hex:rq,buildAnchorPayload:yse,verifyAnchorHash:bse,parseAnchorPayload:_se}});var z1=k((fme,aq)=>{"use strict";v();var oq=ds();function wse(){var e=oq.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function Sse(e){return oq.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}aq.exports={uuid4:wse,randomHex:Sse}});var lq=k((hme,cq)=>{"use strict";v();var ia=Te(),H7=ia.crypto.Hash,j7=ia.crypto.ECDSA,sq=ia.crypto.Signature,z7=ia.PrivateKey,Tr=ia.util.preconditions,lme=xt(),xse=z1();function uq(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof ia.PublicKey?t.issuerPublicKey:ia.PublicKey.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?ia.PublicKey.fromString(i):null}catch{return null}}var Kl={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},fq={create:function(e,t,r,i,n,o){o=o||{},Tr.checkArgument(typeof e=="string","Right type must be string"),Tr.checkArgument(typeof t=="string","Issuer DID must be string"),Tr.checkArgument(typeof r=="string","Subject DID must be string"),Tr.checkArgument(i&&typeof i=="object","Claim must be object");var a=Object.values(Kl);Tr.checkArgument(a.includes(e),"Invalid right type: "+e);var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:i,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(s.credentialSubject.metadata=o.metadata),s},prepareRightToken:function(e,t,r,i,n,o){o=o||{},Tr.checkArgument(typeof e=="string","Right type must be string"),Tr.checkArgument(typeof t=="string","Issuer DID must be string"),Tr.checkArgument(typeof r=="string","Subject DID must be string"),Tr.checkArgument(i&&typeof i=="object","Claim must be object"),Tr.checkArgument(n instanceof z7,"Invalid issuer private key");var a=Object.values(Kl);Tr.checkArgument(a.includes(e),"Invalid right type: "+e);try{var s=this.create(e,t,r,i,n,o),u=this._signToken(s,n);return{success:!0,rightToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:u,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,subject:r,issuedAt:u.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:u.id,issuer:t,subject:r,rightType:e}}}}}catch(c){return{success:!1,error:c.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:n.rightType,issuer:n.issuerDID,subject:n.subjectDID,result:n.valid,verifiedAt:n.verifiedAt}},updateTokenStatus:n.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:n.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,i){i=i||{},Tr.checkArgument(e&&typeof e=="object","Invalid token"),Tr.checkArgument(typeof t=="string","New owner DID must be string"),Tr.checkArgument(r instanceof z7,"Invalid current owner key");try{var n=this.prepareRightTokenVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+n.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,a=uq({issuer:o},{issuerPublicKey:i.currentOwnerPublicKey});if(!a)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==a.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:i.reason||"ownership_transfer",consideration:i.consideration||null}},u=this._signToken(s,r),c=JSON.parse(JSON.stringify(e));c.id="urn:uuid:"+this._generateUUID(),c.issuanceDate=new Date().toISOString(),c.credentialSubject.id=t,c.credentialSubject.transferHistory=c.credentialSubject.transferHistory||[],c.credentialSubject.transferHistory.push({transferId:u.id,transferDate:u.issuanceDate,from:e.credentialSubject.id,to:t}),delete c.proof;var l=this._signToken(c,r);return{success:!0,newToken:l,transferProof:u,transferId:u.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:l.id,transferProof:u,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:u.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:u.id,transferDate:u.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:l.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:l.id,transferId:u.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:u.issuanceDate}}}}}catch(m){return{success:!1,error:m.message}}},prepareObligationToken:function(e,t,r,i){Tr.checkArgument(e&&typeof e=="object","Invalid right token"),Tr.checkArgument(typeof t=="string","Obligor DID must be string"),Tr.checkArgument(r&&typeof r=="object","Obligation must be object"),Tr.checkArgument(i instanceof z7,"Invalid issuer key");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(n,i);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(a){return{success:!1,error:a.message}}},prepareRightTypeValidation:function(e){Tr.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(Kl),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return Kl},verifyToken:function(e,t){var r=[];try{if(Tr.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var i=t instanceof ia.PublicKey?t:ia.PublicKey.fromString(t),n=this._canonicalizeToken(e),o=H7.sha256(h.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var a=e.proof.jws.split(".");if(a.length!==3||!a[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var s=sq.fromDER(h.Buffer.from(a[2],"base64url")),u=new j7;return u.hashbuf=o,u.sig=s,u.pubkey=i,u.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(c){return r.push(c.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=H7.sha256(h.Buffer.from(r)),n=new j7;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=t.toDER().toString("base64url");return i+".."+n},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=H7.sha256(h.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=uq(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=sq.fromDER(h.Buffer.from(a[2],"base64url")),u=new j7;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);i<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var a=new Date(e.credentialSubject.validUntil);i>a&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(Kl);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return xse.uuid4()}};fq.RightTypes=Kl;cq.exports=fq});var pq=k((pme,dq)=>{"use strict";v();var hq=Te(),K1=hq.crypto.Hash,$i=hq.util.preconditions,Ese=z1(),Kf={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},Ose={prepareClaimValidation:function(e,t){try{$i.checkArgument(e&&typeof e=="object","Invalid claim"),$i.checkArgument(typeof t=="string","Schema name must be string");var r=Kf[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var i=[],n=[];this._validateObject(e,r,"",i,n);var o={valid:i.length===0,errors:i,warnings:n,schema:t,claimHash:this.hash(e),canonical:this.canonicalize(e)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(a){return{success:!1,error:"Validation preparation failed: "+a.message}}},prepareClaimAttestation:function(e,t,r){try{$i.checkArgument(e&&typeof e=="object","Invalid claim"),$i.checkArgument(typeof t=="string","Schema name must be string"),$i.checkArgument(r&&typeof r=="object","Invalid attestor");var i=this.prepareClaimValidation(e,t);if(!i.success||!i.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:i};var n={type:"LTP_CLAIM_ATTESTATION",claimHash:i.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=K1.sha256(h.Buffer.from(this.canonicalize(n))).toString("hex");return n.attestationHash=o,{success:!0,attestation:n,claim:e,validation:i.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+i.validation.claimHash+"/attestations",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:i.validation.claimHash,attestorDid:n.attestor.did,attestationHash:o}}}}}catch(a){return{success:!1,error:"Attestation preparation failed: "+a.message}}},prepareClaimDispute:function(e,t,r){try{$i.checkArgument(typeof e=="string","Claim hash must be string"),$i.checkArgument(t&&typeof t=="object","Invalid disputant"),$i.checkArgument(r&&typeof r=="object","Invalid dispute");var i={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},n=K1.sha256(h.Buffer.from(this.canonicalize(i))).toString("hex");return i.disputeHash=n,{success:!0,dispute:i,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:i.disputant.did,disputeHash:n}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:n,priority:i.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{$i.checkArgument(Array.isArray(e),"Claims must be array"),$i.checkArgument(typeof t=="string","Schema name must be string");var r=[],i=[],n=0;e.forEach(function(s,u){try{var c=this.prepareClaimValidation(s,t);c.success&&c.validation.valid&&n++,r.push({index:u,result:c})}catch(l){i.push({index:u,error:l.message})}}.bind(this));var o=this._generateBatchId(),a=K1.sha256(h.Buffer.from(JSON.stringify(r.map(s=>s.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:a,totalClaims:e.length,validClaims:n,invalidClaims:e.length-n,validations:r,errors:i,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:a,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:n,invalid:e.length-n}}}}}}catch(s){return{success:!1,error:"Bulk validation preparation failed: "+s.message}}},canonicalize:function(e){$i.checkArgument(e&&typeof e=="object","Invalid claim");var t=this._sortObjectKeys(e);return JSON.stringify(t)},hash:function(e){var t=this.canonicalize(e);return K1.sha256(h.Buffer.from(t)).toString("hex")},prepareClaimTemplate:function(e,t){t=t||{};try{var r=Kf[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var i=this._createTemplateFromSchema(r),n=this._generateFormStructure(r);return{success:!0,schemaName:e,template:i,schema:r,formStructure:n,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:n,template:i}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:i,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return Kf},getSchemaNames:function(){return Object.keys(Kf)},getSchema:function(e){return Kf[e]||null},addSchema:function(e,t){$i.checkArgument(typeof e=="string","Schema name must be string"),$i.checkArgument(t&&typeof t=="object","Invalid schema"),Kf[e]=t},createTemplate:function(e){var t=Kf[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return K1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return Ese.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r],n={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(i),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(i)};i.enum&&(n.options=i.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(n)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.pattern&&(t[r]=i.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.enum&&(t[r]=i.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,i,n){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||i.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var a=this._getFieldPath(r,o),s=t.properties[o];s?this._validateValue(e[o],s,a,i,n):n.push("Unknown field: "+a)}.bind(this))):this._validateValue(e,t,r,i,n)},_validateValue:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&i.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateValue(e[a],t.items,r+"["+a+"]",i,n);t.type==="object"&&this._validateObject(e,t,r,i,n)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};dq.exports=Ose});var mq=k((vme,vq)=>{"use strict";v();var gq=Te(),V1=gq.crypto.Hash,Vl=gq.util.preconditions,Ise={prepareTokenCommitment:function(e,t){t=t||{},Vl.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,commitment:r,opReturnData:i,txTemplate:n,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},Vl.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,batchCommitment:r,opReturnData:i,txTemplate:n,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){Vl.checkArgument(e&&typeof e=="object","Invalid token"),Vl.checkArgument(typeof t=="string","Transaction ID must be string");try{var i=this._createCommitment(e,{}),n=this._extractOpReturn(r);if(!n)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(i,n);return{valid:o,chainVerified:!1,txid:t,commitment:i,anchorData:n,verifiedAt:new Date().toISOString()}}catch(a){return{valid:!1,error:a.message}}},formatRevocation:function(e,t){Vl.checkArgument(typeof e=="string","Token ID must be string"),Vl.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},i=V1.sha256(h.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:i,opReturnData:this._formatOpReturn({hash:i,type:"REVOCATION"},{})}}catch(n){return{success:!1,error:n.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),i={type:"LTP_TOKEN",tokenHash:V1.sha256(h.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},n=V1.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex");return{hash:n,data:i,canonical:r}},_createBatchCommitment:function(e,t){var r=[],i=[];e.forEach(function(s){var u=this._createCommitment(s,t);r.push(u.hash),i.push(s.id)}.bind(this));var n=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:n,tokenCount:e.length,tokenIds:i,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},a=V1.sha256(h.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:a,data:o,merkleRoot:n,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",i=e.hash;return{prefix:r,data:i,full:r+"."+i,bytes:h.Buffer.from(r+"."+i,"utf8"),size:h.Buffer.from(r+"."+i,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(i){throw new Error("Failed to create transaction template: "+i.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var i=r.script.replace("OP_RETURN ","");return{raw:i,decoded:h.Buffer.from(i,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=t[i+1]||n,a=h.Buffer.concat([h.Buffer.from(n,"hex"),h.Buffer.from(o,"hex")]),s=V1.sha256(a).toString("hex");r.push(s)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,i=148;return{base:t+r,withOneInput:t+r+i,bytesPerInput:i}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};vq.exports=Ise});var _q=k((yme,bq)=>{"use strict";v();var Gl=Te(),fo=Gl.crypto.Hash,yq=Gl.crypto.ECDSA,Ase=Gl.crypto.Signature,Pse=Gl.PrivateKey,Ii=Gl.util.preconditions,Tse={prepareSignatureProof:function(e,t,r){r=r||{},Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t instanceof Pse,"Invalid private key");try{var i=this._canonicalizeForSigning(e),n=fo.sha256(h.Buffer.from(i)),o=new yq;o.hashbuf=n,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var a=o.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(n,a),proofValue:a.toDER().toString("hex")};return{success:!0,proof:s,tokenHash:n.toString("hex"),canonical:i,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:n.toString("hex"),proof:s,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:n.toString("hex"),signature:a.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSignatureVerification:function(e,t){try{if(Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),i=fo.sha256(h.Buffer.from(r)),n=Ase.fromDER(h.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:i.toString("hex"),signature:n.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},a=new yq;a.hashbuf=i,a.sig=n,a.pubkey=Gl.PublicKey.fromString(t);var s=a.verify()===!0;return{success:!0,verification:{valid:s,tokenHash:i.toString("hex"),signatureValid:s,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:i.toString("hex"),result:s,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:s,verifier:t}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosure:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(Array.isArray(t),"Revealed fields must be array"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=this._createFieldCommitments(e,r),n=this._createMerkleTree(i),o=[],a=[];t.forEach(function(u){var c=this._getNestedValue(e,u),l=this._findFieldCommitment(i,u);if(l){o.push({path:u,value:c,commitment:l.hash,salt:l.salt});var m=this._generateMerkleProof(n,l.index);a.push({path:u,leafIndex:l.index,proof:m})}}.bind(this));var s={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:n.root,disclosures:o,merkleProofs:a,totalFields:i.length};return{success:!0,proof:s,hiddenFieldCount:i.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:s,merkleRoot:n.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:s,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:i.length,disclosedAt:new Date().toISOString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(Ii.checkArgument(e&&typeof e=="object","Invalid proof"),Ii.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],i=[];e.disclosures.forEach(function(o,a){var s=e.merkleProofs[a],u=this._hashField(o.path,o.value,o.salt);if(u!==o.commitment){i.push("Invalid commitment for field: "+o.path);return}var c=this._verifyMerkleProof(o.commitment,s.leafIndex,s.proof,e.merkleRoot);c?r.push({path:o.path,value:o.value,verified:!0}):i.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var n={valid:i.length===0,errors:i,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:n.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:i.length,result:n.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=t.requirements||[],n=[],o=!0;i.forEach(function(s){var u=this._checkLegalRequirement(e,s);n.push(u),u.satisfied||(o=!1)}.bind(this));var a={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:n,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:a,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:a,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:n}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:n.filter(s=>!s.satisfied)}}}}}catch(s){return{success:!1,error:s.message}}},prepareZeroKnowledgeProof:function(e,t,r){Ii.checkArgument(e&&typeof e=="object","Invalid token"),Ii.checkArgument(t&&typeof t=="object","Invalid statement"),Ii.checkArgument(typeof r=="string","Nonce must be string");try{var i=fo.sha256(h.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),n={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:i,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:n,commitment:i,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:n,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:n,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var i={challenge:fo.sha256(h.Buffer.from(t.claim+r)).toString("hex"),response:fo.sha256(h.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:fo.sha256(h.Buffer.from(r+e.id+t.predicate)).toString("hex")};return i},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],i=0;return this._traverseObject(e,"",function(n,o){if(n!=="proof"&&n!=="tokenHash"){var a=fo.sha256(h.Buffer.from(t+n+i)).toString("hex"),s=this._hashField(n,o,a);r.push({path:n,value:o,salt:a,hash:s,index:i}),i++}}.bind(this)),r},_hashField:function(e,t,r){var i=e+":"+JSON.stringify(t)+":"+r;return fo.sha256(h.Buffer.from(i)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(l){return l.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],i=t;i.length>1;){for(var n=[],o=0;o<i.length;o+=2){var a=i[o],s=i[o+1]||a,u=h.Buffer.concat([h.Buffer.from(a,"hex"),h.Buffer.from(s,"hex")]),c=fo.sha256(u).toString("hex");n.push(c)}r.push(n),i=n}return{root:i[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],i=t,n=0;n<e.levels.length-1;n++){var o=e.levels[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r},_verifyMerkleProof:function(e,t,r,i){for(var n=e,o=t,a=0;a<r.length;a++){var s=r[a],u=o%2===0,c;s.isLeft?c=h.Buffer.concat([h.Buffer.from(s.hash,"hex"),h.Buffer.from(n,"hex")]):c=h.Buffer.concat([h.Buffer.from(n,"hex"),h.Buffer.from(s.hash,"hex")]),n=fo.sha256(c).toString("hex"),o=Math.floor(o/2)}return n===i},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(i,n){var o=t+"["+n+"]";this._traverseObject(i,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(i){var n=t?t+"."+i:i;this._traverseObject(e[i],n,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var i=new Date,n=new Date(e.issuanceDate);return{requirement:t.type,satisfied:n<=i};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var i={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return fo.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};bq.exports=Tse});var xq=k((Sme,Sq)=>{"use strict";v();var O5=Te(),G1=O5.crypto.Hash,_me=O5.Address,wme=O5.Transaction,Di=O5.util.preconditions,wq=z1(),kse={prepareRegistry:function(e){e=e||{},Di.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},Di.checkArgument(e&&typeof e=="object","Invalid token"),Di.checkArgument(t&&typeof t=="object","Invalid registry config");try{var i=this._validateTokenForRegistration(e,t);if(!i.valid)return{success:!1,error:"Token validation failed: "+i.error};var n={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:i.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:n.registeredAt,metadata:{status:n.status,tokenType:e.type,compliance:n.compliance}});return{success:!0,registrationRecord:n,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:i,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:n},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenApproval:function(e,t,r){try{Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(typeof t=="string","Approver must be string"),Di.checkArgument(r&&typeof r=="object","Invalid registry config");var i={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},n=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:i.approvedAt});return{success:!0,approvalData:i,auditEntry:n,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:n}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(t&&typeof t=="object","Invalid revocation"),Di.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var i={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},n={tokenId:e,status:"REVOKED",revokedAt:i.revokedAt,revocationReason:i.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:i.revokedAt,metadata:{reason:i.reason,legalBasis:i.legalBasis}});return{success:!0,revocationRecord:i,statusUpdate:n,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:i},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenStatusQuery:function(e,t){try{return Di.checkArgument(typeof e=="string","Token ID must be string"),Di.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{Di.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var i=e.offset||0,n=e.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(a){return{success:!1,error:a.message}}},prepareStatisticsQuery:function(e){return Di.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},Di.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var i=t.offset||0,n=t.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+wq.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,G1.sha256(h.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return G1.sha256(h.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],i=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),i=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),i=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),i=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),i=!1),{valid:i,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+wq.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return G1.sha256(h.Buffer.from(t)).toString("hex").substring(0,16)}};Sq.exports=kse});var Aq=k((Eme,Iq)=>{"use strict";v();var Vs=Te(),K7=Vs.crypto.Hash,Eq=Vs.crypto.ECDSA,Rse=Vs.crypto.Signature,Oq=Vs.PrivateKey,Xi=Vs.util.preconditions,Bse=z1();function Mse(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Vs.PublicKey?t.issuerPublicKey:Vs.PublicKey.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?Vs.PublicKey.fromString(i):null}catch{return null}}var I5={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},Zl={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},Li={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},A5={prepareObligationToken:function(e,t,r,i,n,o){o=o||{},Xi.checkArgument(typeof e=="string","Obligation type must be string"),Xi.checkArgument(typeof t=="string","Issuer DID must be string"),Xi.checkArgument(typeof r=="string","Obligor DID must be string"),Xi.checkArgument(i&&typeof i=="object","Obligation must be object"),Xi.checkArgument(n instanceof Oq,"Invalid issuer private key");var a=Object.values(I5);Xi.checkArgument(a.includes(e),"Invalid obligation type: "+e);try{var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:i,jurisdiction:o.jurisdiction||"US",priority:o.priority||Zl.MEDIUM,status:Li.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(s.credentialSubject.metadata=o.metadata);var u=this._signToken(s,n);return{success:!0,obligationToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:u,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,obligor:r,issuedAt:u.issuanceDate,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:u.id,issuer:t,obligor:r,obligationType:e,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},scheduleReminders:s.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:u.id,obligor:r,dueDate:s.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(c){return{success:!1,error:c.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateObligationType(e,r),this._validateObligationStatus(e,r,i),this._validateObligationPriority(e,i);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt,isOverdue:n.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:n.obligationType,issuer:n.issuerDID,obligor:n.obligorDID,result:n.valid,verifiedAt:n.verifiedAt}},updateStatus:n.isOverdue&&e.credentialSubject.status===Li.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:Li.OVERDUE,updatedAt:n.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,i){i=i||{},Xi.checkArgument(e&&typeof e=="object","Invalid token"),Xi.checkArgument(t&&typeof t=="object","Invalid fulfillment"),Xi.checkArgument(r instanceof Oq,"Invalid obligor key");try{var n=this.prepareObligationVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+n.verification.errors.join(", ")};if(e.credentialSubject.status===Li.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===Li.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},a=this._signToken(o,r),s=o.credentialSubject.completionPercentage>=100?Li.COMPLETED:Li.IN_PROGRESS;return{success:!0,fulfillmentRecord:a,newStatus:s,fulfillmentId:a.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:a,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:s,fulfillmentId:a.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:s}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(u){return{success:!1,error:u.message}}},prepareObligationBreachAssessment:function(e,t,r){Xi.checkArgument(e&&typeof e=="object","Invalid token"),Xi.checkArgument(t&&typeof t=="object","Invalid breach details"),Xi.checkArgument(r&&typeof r=="object","Invalid assessor");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},n=K7.sha256(h.Buffer.from(JSON.stringify(i))).toString("hex");return i.credentialSubject.assessmentHash=n,{success:!0,breachAssessment:i,breachId:i.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:i,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:Li.BREACHED,breachId:i.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:i.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,assessedAt:i.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},Xi.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},i=new Date,n=new Date(i.getTime()+10080*60*1e3);return e.forEach(function(o){var a={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var s=new Date(o.credentialSubject.dueDate);a.isDueSoon=s<=n&&s>i}r.summary.byStatus[a.status]=(r.summary.byStatus[a.status]||0)+1,r.summary.byPriority[a.priority]=(r.summary.byPriority[a.priority]||0)+1,r.summary.byType[a.type]=(r.summary.byType[a.type]||0)+1,a.isOverdue&&r.summary.overdue++,a.isDueSoon&&r.summary.dueSoon++,a.status===Li.COMPLETED&&r.summary.completed++,a.isOverdue&&a.priority===Zl.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),a.isDueSoon&&a.priority===Zl.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(a)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return I5},getObligationPriority:function(){return Zl},getObligationStatus:function(){return Li},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=K7.sha256(h.Buffer.from(r)),n=new Eq;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=K7.sha256(h.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=Mse(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=Rse.fromDER(h.Buffer.from(a[2],"base64url")),u=new Eq;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);i<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var a=new Date(e.credentialSubject.expirationDate);i>a&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(I5);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var i=Object.values(Li);i.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===Li.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(Zl);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==Li.COMPLETED},_generateUUID:function(){return Bse.uuid4()}};A5.ObligationTypes=I5;A5.ObligationPriority=Zl;A5.ObligationStatus=Li;Iq.exports=A5});var kq=k((Ime,Tq)=>{"use strict";v();var Vf=lq(),P5=pq(),Z1=mq(),V7=_q(),na=xq(),Nse=Aq(),Pq=Te(),G7=Pq.PrivateKey,Ji=Pq.util.preconditions,wt=function(e){return this instanceof wt?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=na.createRegistry(this.config.registry)),this):new wt(e)};wt.prototype.createRightToken=function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid right data"),Ji.checkArgument(t instanceof G7,"Invalid private key"),r=r||{};try{var i=Vf.create(e.type,e.owner,e.owner,e,t,r);if(!i)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(i=Vf._signToken(i,t)),r.anchor){var n=Z1.anchorToken(i,r.anchor);n.success&&(i.anchorTx=n.txid,i.anchorBlock=n.blockHeight)}if(this.registry&&r.register!==!1){var o=na.registerToken(this.registry,i,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(i.registrationId=o.registrationId,i.registrationStatus=o.status)}return{success:!0,token:i,type:"LegalRightToken"}}catch(a){return{success:!1,error:a.message}}};wt.prototype.validateClaim=function(e,t){return P5.validate(e,t)};wt.prototype.createSelectiveDisclosure=function(e,t,r){return V7.prepareSelectiveDisclosure(e,t,r)};wt.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:Vf.verifyToken(e,t)};wt.prototype.transferRight=function(e,t,r,i){Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(typeof t=="string","New owner must be string"),Ji.checkArgument(r instanceof G7,"Invalid owner key"),i=i||{};try{var n=this.verifyToken(e,r.toPublicKey().toString());if(!n.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=Vf.prepareRightTokenTransfer(e,t,r,i);if(!o.success)return{success:!1,error:o.error};var a=o.newToken,s=o.transferProof;if(i.anchor){var u=Z1.anchorToken(a,i.anchor);u.success&&(a.transferAnchorTx=u.txid)}if(this.registry){var c=na.registerToken(this.registry,a,{registeredBy:i.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});c.success&&(a.registrationId=c.registrationId)}return{success:!0,token:a,transferId:s.id,transferredAt:s.issuanceDate,transferProof:s}}catch(l){return{success:!1,error:l.message}}};wt.prototype.createObligation=function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid right token"),Ji.checkArgument(t&&typeof t=="object","Invalid obligation data"),Ji.checkArgument(r instanceof G7,"Invalid private key");try{var i=Vf.prepareObligationToken(e,t.obligor,t,r);return i.success?{success:!0,obligation:i.obligationToken,rightTokenId:e.id}:{success:!1,error:i.error}}catch(n){return{success:!1,error:n.message}}};wt.prototype.revokeToken=function(e,t,r){return Ji.checkArgument(typeof e=="string","Token ID must be string"),Ji.checkArgument(t&&typeof t=="object","Invalid revocation data"),Ji.checkArgument(typeof r=="string","Authority must be string"),this.registry?na.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};wt.prototype.checkTokenStatus=function(e){return Ji.checkArgument(typeof e=="string","Token ID must be string"),this.registry?na.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};wt.prototype.searchTokens=function(e){return this.registry?na.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};wt.prototype.getRegistryStats=function(){return this.registry?na.getStatistics(this.registry):{error:"No registry available"}};wt.prototype.createLegalValidityProof=function(e,t,r){return V7.prepareLegalValidityProof(e,t,r)};wt.prototype.anchorTokenBatch=function(e,t){return Z1.anchorBatch(e,t)};wt.prototype.verifyAnchor=function(e,t){return Z1.verifyAnchor(e,t)};wt.prototype.getRightTypes=function(){return Vf.getRightTypes()};wt.prototype.getClaimSchemas=function(){return P5.getSchemas()};wt.prototype.createRegistry=function(e){return this.registry=na.createRegistry(e),this.registry};wt.prototype.setRegistry=function(e){Ji.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};wt.create=function(e){return new wt(e)};wt.createRightToken=function(e,t,r){var i=new wt;return i.createRightToken(e,t,r)};wt.validateClaim=function(e,t){return P5.validate(e,t)};wt.verifyToken=function(e,t){var r=new wt;return r.verifyToken(e,t)};wt.createRegistry=function(e){return na.createRegistry(e)};wt.Right=Vf;wt.Claim=P5;wt.Anchor=Z1;wt.Proof=V7;wt.Registry=na;wt.Obligation=Nse;Tq.exports=wt});var Te=k((Pme,Rq)=>{"use strict";v();var j=Rq.exports;j.deps=j.deps||{};j.deps._=xt();j.deps.Buffer=typeof h.Buffer<"u"?h.Buffer:null;if(typeof window>"u")j.deps.bnjs=Nn(),j.deps.bs58=Y2();else{try{j.deps.bnjs=Nn()}catch{}try{j.deps.bs58=Y2()}catch{}}j.version="v"+Km();j.versionGuard=function(e){if(e!==void 0){var t=`
99
99
  More than one instance of bsv found.
100
100
  Please make sure to require bsv and check that submodules do
101
- not also include their own bsv dependency.`;console.warn(t)}};j.versionGuard(globalThis._bsv);globalThis._bsv=j.version;j.isHardened=!0;j.hardenedBy="SmartLedger";j.baseVersion="v1.5.6";j.securityFeatures=["canonical-signatures","malleability-protection","enhanced-validation","elliptic-patches"];j.crypto={};j.crypto.BN=fr();j.crypto.ECDSA=a6();j.crypto.Hash=cr();j.crypto.Random=ds();j.crypto.Point=vn();j.crypto.Signature=Vr();j.crypto.Shamir=R4();j.crypto.SmartVerify=g6();j.crypto.EllipticFixed=v6();j.encoding={};j.encoding.Base58=E0();j.encoding.Base58Check=tl();j.encoding.BufferReader=Da();j.encoding.BufferWriter=Wn();j.encoding.Varint=al();j.util={};j.util.js=pi();j.util.preconditions=Bt();j.errors=hn();j.Address=hf();j.Block=bB();j.MerkleBlock=F4();j.BlockHeader=X0();j.SPV=BB();j.HDPrivateKey=V4();j.HDPublicKey=K4();j.Networks=Ss();j.Opcode=Yp();j.PrivateKey=V0();j.PublicKey=$n();j.Script=bn();j.Transaction=ks();j.Input=ks().Input;j.Output=ks().Output;j.UnspentOutput=ks().UnspentOutput;j.Message=XB();j.Mnemonic=PM();j.ECIES=oN();j.Signature=Vr();j.Shamir=R4();j.SmartLedger={version:j.version,hardenedBy:j.hardenedBy,baseVersion:j.baseVersion,securityFeatures:j.securityFeatures,SmartVerify:g6(),EllipticFixed:v6()};j.SmartVerify=g6();j.EllipticFixed=v6();try{j.SmartContract=xC()}catch(e){typeof window>"u"&&console.warn("SmartContract module not available:",e.message)}try{j.BrowserUTXOManager=EC()}catch(e){typeof window>"u"&&console.warn("[bsv] BrowserUTXOManager failed to load:",e.message)}if(typeof window>"u"&&typeof Fr=="function")try{Z7=!1,Object.defineProperty(j,"SmartUTXO",{configurable:!0,enumerable:!0,get:function(){return!Z7&&!(A.default.env&&A.default.env.BSV_HIDE_DEPRECATIONS)&&(Z7=!0,console.warn("[bsv] bsv.SmartUTXO is a development-only simulator and is deprecated; it will be removed in v6.0.0. Import directly: require('@smartledger/bsv/lib/smartutxo'). Set BSV_HIDE_DEPRECATIONS=1 to silence this warning.")),T5||(T5=w8()),T5}}),j.SmartMiner=IC(),j.CustomScriptHelper=PC()}catch{}var T5,Z7;j.Ordinals=cD();j.GDAF=W7();try{j.DIDWeb=hD()}catch(e){typeof window>"u"&&console.warn("[bsv] DIDWeb module failed to load:",e.message)}try{j.VcJwt=c7()}catch(e){typeof window>"u"&&console.warn("[bsv] VcJwt module failed to load:",e.message)}try{j.StatusList=tq()}catch(e){typeof window>"u"&&console.warn("[bsv] StatusList module failed to load:",e.message)}try{j.Anchor=nq()}catch(e){typeof window>"u"&&console.warn("[bsv] Anchor module failed to load:",e.message)}j.createDID=function(e){var t=new j.GDAF;return t.createDID(e)};j.resolveDID=function(e){var t=new j.GDAF;return t.resolveDID(e)};j.createEmailCredential=function(e,t,r,i){var n=new j.GDAF;return n.createEmailCredential(e,t,r,i)};j.createAgeCredential=function(e,t,r,i,n){var o=new j.GDAF;return o.createAgeCredential(e,t,r,i,n)};j.createKYCCredential=function(e,t,r,i,n){var o=new j.GDAF;return o.createKYCCredential(e,t,r,i,n)};j.verifyCredential=function(e,t){var r=new j.GDAF;return r.verifyCredential(e,t)};j.validateCredential=function(e,t){var r=new j.GDAF;return r.validateCredential(e,t)};j.generateSelectiveProof=function(e,t,r){var i=new j.GDAF;return i.generateSelectiveProof(e,t,r)};j.generateAgeProof=function(e,t,r){var i=new j.GDAF;return i.generateAgeProof(e,t,r)};j.verifyAgeProof=function(e,t,r){var i=new j.GDAF;return i.verifyAgeProof(e,t,r)};j.createPresentation=function(e,t,r,i){var n=new j.GDAF;return n.createPresentation(e,t,r,i)};j.getCredentialSchemas=function(){var e=new j.GDAF;return e.getAllSchemas()};j.createCredentialTemplate=function(e){var t=new j.GDAF;return t.createTemplate(e)};j.LTP=kq();j.prepareRightToken=function(e,t,r,i,n,o){return j.LTP.Right.prepareRightToken(e,t,r,i,n,o)};j.prepareRightTokenVerification=function(e,t){return j.LTP.Right.prepareRightTokenVerification(e,t)};j.prepareRightTokenTransfer=function(e,t,r,i){return j.LTP.Right.prepareRightTokenTransfer(e,t,r,i)};j.prepareRightTypeValidation=function(e){return j.LTP.Right.prepareRightTypeValidation(e)};j.prepareObligationToken=function(e,t,r,i,n,o){return j.LTP.Obligation.prepareObligationToken(e,t,r,i,n,o)};j.prepareObligationVerification=function(e,t){return j.LTP.Obligation.prepareObligationVerification(e,t)};j.prepareObligationFulfillment=function(e,t,r,i){return j.LTP.Obligation.prepareObligationFulfillment(e,t,r,i)};j.prepareObligationBreachAssessment=function(e,t,r){return j.LTP.Obligation.prepareObligationBreachAssessment(e,t,r)};j.prepareObligationMonitoringReport=function(e,t){return j.LTP.Obligation.prepareObligationMonitoringReport(e,t)};j.prepareClaimValidation=function(e,t){return j.LTP.Claim.prepareClaimValidation(e,t)};j.prepareClaimAttestation=function(e,t,r){return j.LTP.Claim.prepareClaimAttestation(e,t,r)};j.prepareClaimDispute=function(e,t,r){return j.LTP.Claim.prepareClaimDispute(e,t,r)};j.prepareBulkClaimValidation=function(e,t){return j.LTP.Claim.prepareBulkClaimValidation(e,t)};j.prepareClaimTemplate=function(e,t){return j.LTP.Claim.prepareClaimTemplate(e,t)};j.prepareSignatureProof=function(e,t,r){return j.LTP.Proof.prepareSignatureProof(e,t,r)};j.prepareSignatureVerification=function(e,t){return j.LTP.Proof.prepareSignatureVerification(e,t)};j.prepareSelectiveDisclosure=function(e,t,r){return j.LTP.Proof.prepareSelectiveDisclosure(e,t,r)};j.prepareSelectiveDisclosureVerification=function(e,t){return j.LTP.Proof.prepareSelectiveDisclosureVerification(e,t)};j.prepareLegalValidityProof=function(e,t,r){return j.LTP.Proof.prepareLegalValidityProof(e,t,r)};j.prepareZeroKnowledgeProof=function(e,t,r){return j.LTP.Proof.prepareZeroKnowledgeProof(e,t,r)};j.prepareRegistry=function(e){return j.LTP.Registry.prepareRegistry(e)};j.prepareTokenRegistration=function(e,t,r){return j.LTP.Registry.prepareTokenRegistration(e,t,r)};j.prepareTokenApproval=function(e,t,r){return j.LTP.Registry.prepareTokenApproval(e,t,r)};j.prepareTokenRevocation=function(e,t,r){return j.LTP.Registry.prepareTokenRevocation(e,t,r)};j.prepareTokenStatusQuery=function(e,t){return j.LTP.Registry.prepareTokenStatusQuery(e,t)};j.prepareTokenSearch=function(e,t){return j.LTP.Registry.prepareTokenSearch(e,t)};j.prepareStatisticsQuery=function(e){return j.LTP.Registry.prepareStatisticsQuery(e)};j.prepareAuditLogQuery=function(e,t){return j.LTP.Registry.prepareAuditLogQuery(e,t)};j.prepareTokenCommitment=function(e,t){return j.LTP.Anchor.prepareTokenCommitment(e,t)};j.prepareBatchCommitment=function(e,t){return j.LTP.Anchor.prepareBatchCommitment(e,t)};j.verifyTokenAnchor=function(e,t,r){return j.LTP.Anchor.verifyTokenAnchor(e,t,r)};j.formatRevocation=function(e,t){return j.LTP.Anchor.formatRevocation(e,t)};j.createRightToken=function(e,t,r){var i=new j.LTP;return i.createRightToken(e,t,r)};j.verifyLegalToken=function(e,t){var r=new j.LTP;return r.verifyToken(e,t)};j.validateLegalClaim=function(e,t){var r=new j.LTP;return r.validateClaim(e,t)};j.createSelectiveDisclosure=function(e,t,r){var i=new j.LTP;return i.createSelectiveDisclosure(e,t,r)};j.createLegalRegistry=function(e){return j.LTP.Registry.prepareRegistry(e)};j.createLegalValidityProof=function(e,t,r){var i=new j.LTP;return i.createLegalValidityProof(e,t,r)};j.getRightTypes=function(){return j.LTP.Right.getRightTypes()};j.getObligationTypes=function(){return j.LTP.Obligation.getObligationTypes()};j.getObligationPriority=function(){return j.LTP.Obligation.getObligationPriority()};j.getObligationStatus=function(){return j.LTP.Obligation.getObligationStatus()};j.getClaimSchemas=function(){return j.LTP.Claim.getSchemas()};j.getClaimSchemaNames=function(){return j.LTP.Claim.getSchemaNames()};j.getClaimSchema=function(e){return j.LTP.Claim.getSchema(e)};j.createClaimTemplate=function(e){return j.LTP.Claim.createTemplate(e)};j.canonicalizeClaim=function(e){return j.LTP.Claim.canonicalize(e)};j.hashClaim=function(e){return j.LTP.Claim.hash(e)};j.addCustomClaimSchema=function(e,t){return j.LTP.Claim.addSchema(e,t)};j.Transaction.sighash=qa()});var k5=k((Bme,Mq)=>{"use strict";v();var Gs=Te(),Y7=Gs.PublicKey,W1=Gs.PrivateKey,Bq=Gs.crypto.Hash,An=Gs.util.preconditions,Rme=Gs.errors;function Ct(e){return this instanceof Ct?(this.options=e||{},this.network=this.options.network||"mainnet",this.registry=this.options.registry||null,this):new Ct(e)}Ct.fromPublicKey=function(e,t){t=t||{},typeof e=="string"&&(e=Y7.fromString(e)),An.checkArgument(e instanceof Y7,"Invalid public key");var r=e.toString("hex"),i=t.network||"mainnet",n=t.path||"",o="did:smartledger:"+r;return i!=="mainnet"&&(o+=":"+i),n&&(o+=":"+n),o};Ct.fromPrivateKey=function(e,t){return typeof e=="string"&&(e=W1.fromWIF(e)),An.checkArgument(e instanceof W1,"Invalid private key"),Ct.fromPublicKey(e.toPublicKey(),t)};Ct.parseDID=function(e){if(An.checkArgument(typeof e=="string","DID must be a string"),!e.startsWith("did:smartledger:"))throw new Error("Invalid SmartLedger DID format");var t=e.split(":");if(t.length<3)throw new Error("Invalid DID format");var r={method:"smartledger",identifier:t[2],network:"mainnet",path:""};return t.length>3&&t[3]!==""&&(r.network=t[3]),t.length>4&&(r.path=t.slice(4).join(":")),r};Ct.isValidDID=function(e){try{var t=Ct.parseDID(e);return!(!/^[0-9a-fA-F]{66}$/.test(t.identifier)&&!/^[0-9a-fA-F]{130}$/.test(t.identifier)||!["mainnet","testnet","regtest"].includes(t.network))}catch{return!1}};Ct.getPublicKey=function(e){var t=Ct.parseDID(e);return Y7.fromString(t.identifier)};Ct.createDocument=function(e,t){t=t||{},An.checkArgument(Ct.isValidDID(e),"Invalid DID");var r=Ct.getPublicKey(e),i=e+"#keys-1",n={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/secp256k1-2019/v1"],id:e,verificationMethod:[{id:i,type:"EcdsaSecp256k1VerificationKey2019",controller:e,publicKeyHex:r.toString("hex")}],authentication:[i],assertionMethod:[i],keyAgreement:[i],capabilityInvocation:[i],capabilityDelegation:[i]};return t.services&&Array.isArray(t.services)&&(n.service=t.services),t.verificationMethods&&(n.verificationMethod=n.verificationMethod.concat(t.verificationMethods)),t.created&&(n.created=t.created),t.updated&&(n.updated=t.updated),n};Ct.resolve=async function(e,t){t=t||{};try{An.checkArgument(Ct.isValidDID(e),"Invalid DID");var r=Ct.createDocument(e,t);return{"@context":"https://w3id.org/did-resolution/v1",didDocument:r,didResolutionMetadata:{contentType:"application/did+ld+json",retrieved:new Date().toISOString()},didDocumentMetadata:{method:{published:!0,recoveryCommitment:null,updateCommitment:null}}}}catch(i){return{"@context":"https://w3id.org/did-resolution/v1",didDocument:null,didResolutionMetadata:{error:"notFound",errorMessage:i.message},didDocumentMetadata:{}}}};Ct.verifyOwnership=function(e,t,r){try{var i=Ct.getPublicKey(e),n=Bq.sha256(h.Buffer.isBuffer(r)?r:h.Buffer.from(r,"utf8")),o=Gs.crypto.Signature.fromString(t),a=new Gs.crypto.ECDSA;return a.hashbuf=n,a.pubkey=i,a.sig=o,a.verify()===!0}catch{return!1}};Ct.signMessage=function(e,t){An.checkArgument(t instanceof W1,"Invalid private key");var r=Bq.sha256(h.Buffer.isBuffer(e)?e:h.Buffer.from(e,"utf8")),i=new Gs.crypto.ECDSA;return i.hashbuf=r,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign().toString()};Ct.createProofOfOwnership=function(e,t){An.checkArgument(e instanceof W1,"Invalid private key"),An.checkArgument(typeof t=="string","Challenge must be a string");var r=Ct.fromPrivateKey(e),i=new Date().toISOString(),n=t+":"+i+":"+r,o=Ct.signMessage(n,e);return{type:"EcdsaSecp256k1Signature2019",created:i,verificationMethod:r+"#keys-1",proofPurpose:"authentication",challenge:t,jws:o}};Ct.verifyProofOfOwnership=function(e,t){try{An.checkArgument(e&&typeof e=="object","Invalid proof object"),An.checkArgument(typeof t=="string","DID must be a string");var r=e.challenge+":"+e.created+":"+t;return Ct.verifyOwnership(t,e.jws,r)}catch{return!1}};Ct.createDIDURL=function(e,t){return An.checkArgument(typeof e=="string","DID must be a string"),An.checkArgument(typeof t=="string","Fragment must be a string"),e+"#"+t};Ct.generateTestDID=function(e){e=e||{};var t=new W1,r=Ct.fromPrivateKey(t,e),i=Ct.createDocument(r,e);return{did:r,privateKey:t.toWIF(),publicKey:t.toPublicKey().toString("hex"),document:i}};Mq.exports=Ct});var R5=k((Dme,Dq)=>{"use strict";v();var Wl=Te(),Cse=k5(),Nq=Wl.PrivateKey,Zs=Wl.crypto.Hash,Cq=Wl.crypto.ECDSA,Nme=Wl.crypto.Signature,Ws=Wl.util.preconditions,Cme=xt();function dr(e,t){return this instanceof dr?(typeof e=="string"&&(e=Nq.fromWIF(e)),Ws.checkArgument(e instanceof Nq,"Invalid private key"),this.privateKey=e,this.publicKey=e.toPublicKey(),this.options=t||{},this.did=Cse.fromPrivateKey(e,this.options),this):new dr(e,t)}dr._sortValue=function(e){return Array.isArray(e)?e.map(function(t){return dr._sortValue(t)}):e!==null&&typeof e=="object"?Object.keys(e).sort().reduce(function(t,r){return t[r]=dr._sortValue(e[r]),t},{}):e};dr._canonicalizeJSON=function(e){return JSON.stringify(dr._sortValue(e))};dr._hashCredential=function(e){var t=dr._canonicalizeJSON(e);return Zs.sha256(h.Buffer.from(t,"utf8"))};dr.prototype.createCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid credential subject");var r=new Date().toISOString(),i=t.id||"urn:uuid:"+this._generateUUID(),n={"@context":["https://www.w3.org/2018/credentials/v1"],id:i,type:["VerifiableCredential"],issuer:this.did,issuanceDate:r,credentialSubject:e};return t.type&&(Array.isArray(t.type)?n.type=n.type.concat(t.type):n.type.push(t.type)),t.context&&(Array.isArray(t.context)?n["@context"]=n["@context"].concat(t.context):n["@context"].push(t.context)),t.expirationDate&&(n.expirationDate=t.expirationDate),t.termsOfUse&&(n.termsOfUse=t.termsOfUse),t.evidence&&(n.evidence=t.evidence),t.refreshService&&(n.refreshService=t.refreshService),n};dr.prototype.signCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid credential");var r=JSON.parse(JSON.stringify(e));delete r.proof;var i=dr._hashCredential(r),n=new Cq;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:t.proofPurpose||"assertionMethod",jws:a};t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain);var u=JSON.parse(JSON.stringify(r));return u.proof=s,u.rootHash=i.toString("hex"),u};dr.prototype._createJWSSignature=function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o};dr.prototype.createEmailCredential=function(e,t){t=t||{},Ws.checkArgument(typeof e=="string"&&e.includes("@"),"Invalid email address");var r={id:t.subjectId||"did:smartledger:"+Zs.sha256(h.Buffer.from(e)).toString("hex"),email:e,verified:!0,verificationMethod:"email_verification",verificationTimestamp:new Date().toISOString()},i={type:"EmailVerifiedCredential",context:"https://smartledger.technology/contexts/email/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype.createAgeCredential=function(e,t,r){r=r||{},Ws.checkArgument(typeof e=="number"&&e>0,"Invalid age");var i={id:r.subjectId||"urn:uuid:"+this._generateUUID(),ageOver:e,verified:!0,verificationMethod:"age_verification"};t&&(i.birthDateHash=Zs.sha256(h.Buffer.from(t.toISOString())).toString("hex"));var n={type:"AgeVerifiedCredential",context:"https://smartledger.technology/contexts/age/v1",...r},o=this.createCredential(i,n);return this.signCredential(o,r)};dr.prototype.createKYCCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid KYC data");var r={id:t.subjectId||"urn:uuid:"+this._generateUUID(),kycLevel:e.level||"basic",verified:!0,verificationMethod:"kyc_verification",verificationTimestamp:new Date().toISOString(),verifyingAuthority:e.authority||this.did};e.firstName&&(r.firstNameHash=Zs.sha256(h.Buffer.from(e.firstName)).toString("hex")),e.lastName&&(r.lastNameHash=Zs.sha256(h.Buffer.from(e.lastName)).toString("hex")),e.ssn&&(r.ssnHash=Zs.sha256(h.Buffer.from(e.ssn)).toString("hex"));var i={type:"KYCVerifiedCredential",context:"https://smartledger.technology/contexts/kyc/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype.createOrganizationCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid organization data");var r={id:t.subjectId||"did:smartledger:org:"+Zs.sha256(h.Buffer.from(e.name||"")).toString("hex"),name:e.name,type:e.type||"Organization",verified:!0,verificationMethod:"organization_verification",verificationTimestamp:new Date().toISOString()};e.taxId&&(r.taxIdHash=Zs.sha256(h.Buffer.from(e.taxId)).toString("hex")),e.incorporationState&&(r.incorporationState=e.incorporationState),e.industry&&(r.industry=e.industry);var i={type:"OrganizationCredential",context:"https://smartledger.technology/contexts/organization/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype._generateUUID=function(){var e=Wl.crypto.Random.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")};dr.prototype.createPresentation=function(e,t){t=t||{},Ws.checkArgument(Array.isArray(e),"Credentials must be an array");var r={"@context":["https://www.w3.org/2018/credentials/v1"],type:["VerifiablePresentation"],id:t.id||"urn:uuid:"+this._generateUUID(),holder:this.did,verifiableCredential:e};t.context&&(Array.isArray(t.context)?r["@context"]=r["@context"].concat(t.context):r["@context"].push(t.context));var i=dr._hashCredential(r),n=new Cq;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:"authentication",jws:a};return t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain),r.proof=s,r};dr.prototype.getIssuerInfo=function(){return{did:this.did,publicKey:this.publicKey.toString("hex"),verificationMethod:this.did+"#keys-1"}};Dq.exports=dr});var Fq=k((Fme,Uq)=>{"use strict";v();var Y1=Te(),B5=k5(),$7=R5(),qme=Y1.PublicKey,Ume=Y1.crypto.Hash,Lq=Y1.crypto.ECDSA,Dse=Y1.crypto.Signature,qq=Y1.util.preconditions;function Mt(e){return this instanceof Mt?(this.options=e||{},this.trustedIssuers=this.options.trustedIssuers||[],this):new Mt(e)}Mt.verifyCredential=async function(e,t){t=t||{};try{qq.checkArgument(e&&typeof e=="object","Invalid credential");var r={valid:!1,errors:[],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}},i=Mt._validateStructure(e);r.checks.structure=i.valid,i.valid||(r.errors=r.errors.concat(i.errors));var n=await Mt._verifySignature(e);r.checks.signature=n.valid,n.valid?(r.issuerDID=n.issuerDID,r.verificationMethod=n.verificationMethod):r.errors=r.errors.concat(n.errors);var o=await Mt._validateIssuer(e,t);r.checks.issuer=o.valid,o.valid||(r.errors=r.errors.concat(o.errors)),o.warnings&&(r.warnings=r.warnings.concat(o.warnings));var a=Mt._validateTemporal(e);if(r.checks.temporal=a.valid,a.valid||(r.errors=r.errors.concat(a.errors)),a.warnings&&(r.warnings=r.warnings.concat(a.warnings)),t.schema){var s=Mt._validateSchema(e,t.schema);r.checks.schema=s.valid,s.valid||(r.errors=r.errors.concat(s.errors))}else r.checks.schema=!0;return r.valid=Object.values(r.checks).every(u=>u===!0),r}catch(u){return{valid:!1,errors:["Verification failed: "+u.message],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}}}};Mt.verifyPresentation=async function(e,t){t=t||{};try{qq.checkArgument(e&&typeof e=="object","Invalid presentation");var r={valid:!1,errors:[],warnings:[],credentialResults:[],presentationValid:!1};if(!e.type||!e.type.includes("VerifiablePresentation"))return r.errors.push("Invalid presentation type"),r;if(!e.holder)return r.errors.push("Missing presentation holder"),r;var i=await Mt._verifyPresentationSignature(e);if(r.presentationValid=i.valid,i.valid||(r.errors=r.errors.concat(i.errors)),e.verifiableCredential&&Array.isArray(e.verifiableCredential))for(var n=0;n<e.verifiableCredential.length;n++){var o=e.verifiableCredential[n],a=await Mt.verifyCredential(o,t);r.credentialResults.push({index:n,result:a}),a.valid||r.errors.push("Credential "+n+" is invalid")}var s=r.credentialResults.every(u=>u.result.valid);return r.valid=r.presentationValid&&s,r}catch(u){return{valid:!1,errors:["Presentation verification failed: "+u.message],warnings:[],credentialResults:[],presentationValid:!1}}};Mt._validateStructure=function(e){var t=[];return e["@context"]?Array.isArray(e["@context"])?e["@context"].includes("https://www.w3.org/2018/credentials/v1")||t.push("Missing required W3C credentials context"):t.push("@context must be an array"):t.push("Missing @context"),e.type?Array.isArray(e.type)?e.type.includes("VerifiableCredential")||t.push("Must include VerifiableCredential type"):t.push("type must be an array"):t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof"),{valid:t.length===0,errors:t}};Mt._normalizeDID=function(e){var t=e&&typeof e=="object"?e.id:e;return typeof t!="string"||t.length===0?null:t.split("#")[0]};Mt._verifySignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing proof"]};if(t.type!=="EcdsaSecp256k1Signature2019")return{valid:!1,errors:["Unsupported proof type: "+t.type]};if(!t.verificationMethod)return{valid:!1,errors:["Missing verification method"]};if(!t.jws)return{valid:!1,errors:["Missing JWS signature"]};var r=t.verificationMethod,i=r.split("#")[0],n=Mt._normalizeDID(e.issuer);if(!n)return{valid:!1,errors:["Missing or invalid credential issuer"]};if(n!==i)return{valid:!1,errors:["Verification method DID ("+i+") does not match credential issuer ("+n+")"]};var o=B5.getPublicKey(i),a=JSON.parse(JSON.stringify(e));delete a.proof,delete a.rootHash;var s=$7._hashCredential(a),u=Mt._parseJWSSignature(t.jws),c=new Lq;c.hashbuf=s,c.pubkey=o,c.sig=u;var l=c.verify();return l?{valid:!0,issuerDID:i,verificationMethod:r}:{valid:!1,errors:["Signature verification failed"]}}catch(m){return{valid:!1,errors:["Signature verification error: "+m.message]}}};Mt._parseJWSSignature=function(e){var t=e.split(".");if(t.length!==3)throw new Error("Invalid JWS format");var r=t[2],i=h.Buffer.from(r,"base64url");return Dse.fromDER(i)};Mt._verifyPresentationSignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing presentation proof"]};var r=e.holder,i=B5.getPublicKey(r),n=JSON.parse(JSON.stringify(e));delete n.proof;var o=$7._hashCredential(n),a=Mt._parseJWSSignature(t.jws),s=new Lq;s.hashbuf=o,s.pubkey=i,s.sig=a;var u=s.verify();return{valid:u,errors:u?[]:["Presentation signature verification failed"]}}catch(c){return{valid:!1,errors:["Presentation signature error: "+c.message]}}};Mt._validateIssuer=async function(e,t){var r=[],i=[];try{var n=e.issuer;if(!B5.isValidDID(n))return r.push("Invalid issuer DID format"),{valid:!1,errors:r};var o=await B5.resolve(n);if(!o.didDocument)return r.push("Unable to resolve issuer DID"),{valid:!1,errors:r};if(t.trustedIssuers&&Array.isArray(t.trustedIssuers)){var a=Mt._normalizeDID(n),s=t.trustedIssuers.map(function(u){return Mt._normalizeDID(u)}).filter(Boolean);if(!a||s.indexOf(a)===-1)return r.push("Issuer not in trusted list"),{valid:!1,errors:r,warnings:i}}return{valid:r.length===0,errors:r,warnings:i}}catch(u){return{valid:!1,errors:["Issuer validation error: "+u.message],warnings:i}}};Mt._validateTemporal=function(e){var t=[],r=[],i=new Date;if(e.issuanceDate){var n=new Date(e.issuanceDate);isNaN(n.getTime())?t.push("Invalid issuanceDate format"):n>i&&t.push("Credential issued in the future")}if(e.expirationDate){var o=new Date(e.expirationDate);isNaN(o.getTime())?t.push("Invalid expirationDate format"):o<=i?t.push("Credential has expired"):o<=new Date(i.getTime()+1440*60*1e3)&&r.push("Credential expires within 24 hours")}return{valid:t.length===0,errors:t,warnings:r}};Mt._validateSchema=function(e,t){var r=[];if(t.requiredFields&&t.requiredFields.forEach(function(n){Mt._getNestedProperty(e,n)||r.push("Missing required field: "+n)}),t.requiredTypes){var i=t.requiredTypes.some(function(n){return e.type&&e.type.includes(n)});i||r.push("Missing required credential type")}return{valid:r.length===0,errors:r}};Mt._getNestedProperty=function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)};Mt.verifyCredentialHash=function(e){try{if(!e.rootHash)return!1;var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.rootHash;var r=$7._hashCredential(t),i=h.Buffer.from(e.rootHash,"hex");return h.Buffer.compare(r,i)===0}catch{return!1}};Mt.extractClaims=function(e){try{var t={issuer:e.issuer,subject:e.credentialSubject.id||"unknown",types:e.type||[],issuanceDate:e.issuanceDate,expirationDate:e.expirationDate,claims:{}};return Object.keys(e.credentialSubject).forEach(function(r){r!=="id"&&(t.claims[r]=e.credentialSubject[r])}),t}catch{return null}};Mt.createReport=function(e){var t=[];return t.push("=== Credential Verification Report ==="),t.push("Overall Status: "+(e.valid?"VALID":"INVALID")),t.push(""),t.push("Verification Checks:"),Object.keys(e.checks).forEach(function(r){var i=e.checks[r]?"\u2713":"\u2717";t.push(" "+i+" "+r.charAt(0).toUpperCase()+r.slice(1))}),t.push(""),e.errors.length>0&&(t.push("Errors:"),e.errors.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.warnings.length>0&&(t.push("Warnings:"),e.warnings.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.issuerDID&&t.push("Issuer: "+e.issuerDID),e.verificationMethod&&t.push("Verification Method: "+e.verificationMethod),t.join(`
101
+ not also include their own bsv dependency.`;console.warn(t)}};j.versionGuard(globalThis._bsv);globalThis._bsv=j.version;j.isHardened=!0;j.hardenedBy="SmartLedger";j.baseVersion="v1.5.6";j.securityFeatures=["canonical-signatures","malleability-protection","enhanced-validation","audited-noble-curves","fail-closed-verification"];j.crypto={};j.crypto.BN=fr();j.crypto.ECDSA=a6();j.crypto.Hash=cr();j.crypto.Random=ds();j.crypto.Point=vn();j.crypto.Signature=Vr();j.crypto.Shamir=R4();j.crypto.SmartVerify=g6();j.crypto.EllipticFixed=v6();j.encoding={};j.encoding.Base58=E0();j.encoding.Base58Check=tl();j.encoding.BufferReader=Da();j.encoding.BufferWriter=Wn();j.encoding.Varint=al();j.util={};j.util.js=pi();j.util.preconditions=Bt();j.errors=hn();j.Address=hf();j.Block=bB();j.MerkleBlock=F4();j.BlockHeader=X0();j.SPV=BB();j.HDPrivateKey=V4();j.HDPublicKey=K4();j.Networks=Ss();j.Opcode=Yp();j.PrivateKey=V0();j.PublicKey=$n();j.Script=bn();j.Transaction=ks();j.Input=ks().Input;j.Output=ks().Output;j.UnspentOutput=ks().UnspentOutput;j.Message=XB();j.Mnemonic=PM();j.ECIES=oN();j.Signature=Vr();j.Shamir=R4();j.SmartLedger={version:j.version,hardenedBy:j.hardenedBy,baseVersion:j.baseVersion,securityFeatures:j.securityFeatures,SmartVerify:g6(),EllipticFixed:v6()};j.SmartVerify=g6();j.EllipticFixed=v6();try{j.SmartContract=xC()}catch(e){typeof window>"u"&&console.warn("SmartContract module not available:",e.message)}try{j.BrowserUTXOManager=EC()}catch(e){typeof window>"u"&&console.warn("[bsv] BrowserUTXOManager failed to load:",e.message)}if(typeof window>"u"&&typeof Fr=="function")try{Z7=!1,Object.defineProperty(j,"SmartUTXO",{configurable:!0,enumerable:!0,get:function(){return!Z7&&!(A.default.env&&A.default.env.BSV_HIDE_DEPRECATIONS)&&(Z7=!0,console.warn("[bsv] bsv.SmartUTXO is a development-only simulator and is deprecated; it will be removed in v6.0.0. Import directly: require('@smartledger/bsv/lib/smartutxo'). Set BSV_HIDE_DEPRECATIONS=1 to silence this warning.")),T5||(T5=w8()),T5}}),j.SmartMiner=IC(),j.CustomScriptHelper=PC()}catch{}var T5,Z7;j.Ordinals=cD();j.GDAF=W7();try{j.DIDWeb=hD()}catch(e){typeof window>"u"&&console.warn("[bsv] DIDWeb module failed to load:",e.message)}try{j.VcJwt=c7()}catch(e){typeof window>"u"&&console.warn("[bsv] VcJwt module failed to load:",e.message)}try{j.StatusList=tq()}catch(e){typeof window>"u"&&console.warn("[bsv] StatusList module failed to load:",e.message)}try{j.Anchor=nq()}catch(e){typeof window>"u"&&console.warn("[bsv] Anchor module failed to load:",e.message)}j.createDID=function(e){var t=new j.GDAF;return t.createDID(e)};j.resolveDID=function(e){var t=new j.GDAF;return t.resolveDID(e)};j.createEmailCredential=function(e,t,r,i){var n=new j.GDAF;return n.createEmailCredential(e,t,r,i)};j.createAgeCredential=function(e,t,r,i,n){var o=new j.GDAF;return o.createAgeCredential(e,t,r,i,n)};j.createKYCCredential=function(e,t,r,i,n){var o=new j.GDAF;return o.createKYCCredential(e,t,r,i,n)};j.verifyCredential=function(e,t){var r=new j.GDAF;return r.verifyCredential(e,t)};j.validateCredential=function(e,t){var r=new j.GDAF;return r.validateCredential(e,t)};j.generateSelectiveProof=function(e,t,r){var i=new j.GDAF;return i.generateSelectiveProof(e,t,r)};j.generateAgeProof=function(e,t,r){var i=new j.GDAF;return i.generateAgeProof(e,t,r)};j.verifyAgeProof=function(e,t,r){var i=new j.GDAF;return i.verifyAgeProof(e,t,r)};j.createPresentation=function(e,t,r,i){var n=new j.GDAF;return n.createPresentation(e,t,r,i)};j.getCredentialSchemas=function(){var e=new j.GDAF;return e.getAllSchemas()};j.createCredentialTemplate=function(e){var t=new j.GDAF;return t.createTemplate(e)};j.LTP=kq();j.prepareRightToken=function(e,t,r,i,n,o){return j.LTP.Right.prepareRightToken(e,t,r,i,n,o)};j.prepareRightTokenVerification=function(e,t){return j.LTP.Right.prepareRightTokenVerification(e,t)};j.prepareRightTokenTransfer=function(e,t,r,i){return j.LTP.Right.prepareRightTokenTransfer(e,t,r,i)};j.prepareRightTypeValidation=function(e){return j.LTP.Right.prepareRightTypeValidation(e)};j.prepareObligationToken=function(e,t,r,i,n,o){return j.LTP.Obligation.prepareObligationToken(e,t,r,i,n,o)};j.prepareObligationVerification=function(e,t){return j.LTP.Obligation.prepareObligationVerification(e,t)};j.prepareObligationFulfillment=function(e,t,r,i){return j.LTP.Obligation.prepareObligationFulfillment(e,t,r,i)};j.prepareObligationBreachAssessment=function(e,t,r){return j.LTP.Obligation.prepareObligationBreachAssessment(e,t,r)};j.prepareObligationMonitoringReport=function(e,t){return j.LTP.Obligation.prepareObligationMonitoringReport(e,t)};j.prepareClaimValidation=function(e,t){return j.LTP.Claim.prepareClaimValidation(e,t)};j.prepareClaimAttestation=function(e,t,r){return j.LTP.Claim.prepareClaimAttestation(e,t,r)};j.prepareClaimDispute=function(e,t,r){return j.LTP.Claim.prepareClaimDispute(e,t,r)};j.prepareBulkClaimValidation=function(e,t){return j.LTP.Claim.prepareBulkClaimValidation(e,t)};j.prepareClaimTemplate=function(e,t){return j.LTP.Claim.prepareClaimTemplate(e,t)};j.prepareSignatureProof=function(e,t,r){return j.LTP.Proof.prepareSignatureProof(e,t,r)};j.prepareSignatureVerification=function(e,t){return j.LTP.Proof.prepareSignatureVerification(e,t)};j.prepareSelectiveDisclosure=function(e,t,r){return j.LTP.Proof.prepareSelectiveDisclosure(e,t,r)};j.prepareSelectiveDisclosureVerification=function(e,t){return j.LTP.Proof.prepareSelectiveDisclosureVerification(e,t)};j.prepareLegalValidityProof=function(e,t,r){return j.LTP.Proof.prepareLegalValidityProof(e,t,r)};j.prepareZeroKnowledgeProof=function(e,t,r){return j.LTP.Proof.prepareZeroKnowledgeProof(e,t,r)};j.prepareRegistry=function(e){return j.LTP.Registry.prepareRegistry(e)};j.prepareTokenRegistration=function(e,t,r){return j.LTP.Registry.prepareTokenRegistration(e,t,r)};j.prepareTokenApproval=function(e,t,r){return j.LTP.Registry.prepareTokenApproval(e,t,r)};j.prepareTokenRevocation=function(e,t,r){return j.LTP.Registry.prepareTokenRevocation(e,t,r)};j.prepareTokenStatusQuery=function(e,t){return j.LTP.Registry.prepareTokenStatusQuery(e,t)};j.prepareTokenSearch=function(e,t){return j.LTP.Registry.prepareTokenSearch(e,t)};j.prepareStatisticsQuery=function(e){return j.LTP.Registry.prepareStatisticsQuery(e)};j.prepareAuditLogQuery=function(e,t){return j.LTP.Registry.prepareAuditLogQuery(e,t)};j.prepareTokenCommitment=function(e,t){return j.LTP.Anchor.prepareTokenCommitment(e,t)};j.prepareBatchCommitment=function(e,t){return j.LTP.Anchor.prepareBatchCommitment(e,t)};j.verifyTokenAnchor=function(e,t,r){return j.LTP.Anchor.verifyTokenAnchor(e,t,r)};j.formatRevocation=function(e,t){return j.LTP.Anchor.formatRevocation(e,t)};j.createRightToken=function(e,t,r){var i=new j.LTP;return i.createRightToken(e,t,r)};j.verifyLegalToken=function(e,t){var r=new j.LTP;return r.verifyToken(e,t)};j.validateLegalClaim=function(e,t){var r=new j.LTP;return r.validateClaim(e,t)};j.createSelectiveDisclosure=function(e,t,r){var i=new j.LTP;return i.createSelectiveDisclosure(e,t,r)};j.createLegalRegistry=function(e){return j.LTP.Registry.prepareRegistry(e)};j.createLegalValidityProof=function(e,t,r){var i=new j.LTP;return i.createLegalValidityProof(e,t,r)};j.getRightTypes=function(){return j.LTP.Right.getRightTypes()};j.getObligationTypes=function(){return j.LTP.Obligation.getObligationTypes()};j.getObligationPriority=function(){return j.LTP.Obligation.getObligationPriority()};j.getObligationStatus=function(){return j.LTP.Obligation.getObligationStatus()};j.getClaimSchemas=function(){return j.LTP.Claim.getSchemas()};j.getClaimSchemaNames=function(){return j.LTP.Claim.getSchemaNames()};j.getClaimSchema=function(e){return j.LTP.Claim.getSchema(e)};j.createClaimTemplate=function(e){return j.LTP.Claim.createTemplate(e)};j.canonicalizeClaim=function(e){return j.LTP.Claim.canonicalize(e)};j.hashClaim=function(e){return j.LTP.Claim.hash(e)};j.addCustomClaimSchema=function(e,t){return j.LTP.Claim.addSchema(e,t)};j.Transaction.sighash=qa()});var k5=k((Bme,Mq)=>{"use strict";v();var Gs=Te(),Y7=Gs.PublicKey,W1=Gs.PrivateKey,Bq=Gs.crypto.Hash,An=Gs.util.preconditions,Rme=Gs.errors;function Ct(e){return this instanceof Ct?(this.options=e||{},this.network=this.options.network||"mainnet",this.registry=this.options.registry||null,this):new Ct(e)}Ct.fromPublicKey=function(e,t){t=t||{},typeof e=="string"&&(e=Y7.fromString(e)),An.checkArgument(e instanceof Y7,"Invalid public key");var r=e.toString("hex"),i=t.network||"mainnet",n=t.path||"",o="did:smartledger:"+r;return i!=="mainnet"&&(o+=":"+i),n&&(o+=":"+n),o};Ct.fromPrivateKey=function(e,t){return typeof e=="string"&&(e=W1.fromWIF(e)),An.checkArgument(e instanceof W1,"Invalid private key"),Ct.fromPublicKey(e.toPublicKey(),t)};Ct.parseDID=function(e){if(An.checkArgument(typeof e=="string","DID must be a string"),!e.startsWith("did:smartledger:"))throw new Error("Invalid SmartLedger DID format");var t=e.split(":");if(t.length<3)throw new Error("Invalid DID format");var r={method:"smartledger",identifier:t[2],network:"mainnet",path:""};return t.length>3&&t[3]!==""&&(r.network=t[3]),t.length>4&&(r.path=t.slice(4).join(":")),r};Ct.isValidDID=function(e){try{var t=Ct.parseDID(e);return!(!/^[0-9a-fA-F]{66}$/.test(t.identifier)&&!/^[0-9a-fA-F]{130}$/.test(t.identifier)||!["mainnet","testnet","regtest"].includes(t.network))}catch{return!1}};Ct.getPublicKey=function(e){var t=Ct.parseDID(e);return Y7.fromString(t.identifier)};Ct.createDocument=function(e,t){t=t||{},An.checkArgument(Ct.isValidDID(e),"Invalid DID");var r=Ct.getPublicKey(e),i=e+"#keys-1",n={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/secp256k1-2019/v1"],id:e,verificationMethod:[{id:i,type:"EcdsaSecp256k1VerificationKey2019",controller:e,publicKeyHex:r.toString("hex")}],authentication:[i],assertionMethod:[i],keyAgreement:[i],capabilityInvocation:[i],capabilityDelegation:[i]};return t.services&&Array.isArray(t.services)&&(n.service=t.services),t.verificationMethods&&(n.verificationMethod=n.verificationMethod.concat(t.verificationMethods)),t.created&&(n.created=t.created),t.updated&&(n.updated=t.updated),n};Ct.resolve=async function(e,t){t=t||{};try{An.checkArgument(Ct.isValidDID(e),"Invalid DID");var r=Ct.createDocument(e,t);return{"@context":"https://w3id.org/did-resolution/v1",didDocument:r,didResolutionMetadata:{contentType:"application/did+ld+json",retrieved:new Date().toISOString()},didDocumentMetadata:{method:{published:!0,recoveryCommitment:null,updateCommitment:null}}}}catch(i){return{"@context":"https://w3id.org/did-resolution/v1",didDocument:null,didResolutionMetadata:{error:"notFound",errorMessage:i.message},didDocumentMetadata:{}}}};Ct.verifyOwnership=function(e,t,r){try{var i=Ct.getPublicKey(e),n=Bq.sha256(h.Buffer.isBuffer(r)?r:h.Buffer.from(r,"utf8")),o=Gs.crypto.Signature.fromString(t),a=new Gs.crypto.ECDSA;return a.hashbuf=n,a.pubkey=i,a.sig=o,a.verify()===!0}catch{return!1}};Ct.signMessage=function(e,t){An.checkArgument(t instanceof W1,"Invalid private key");var r=Bq.sha256(h.Buffer.isBuffer(e)?e:h.Buffer.from(e,"utf8")),i=new Gs.crypto.ECDSA;return i.hashbuf=r,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign().toString()};Ct.createProofOfOwnership=function(e,t){An.checkArgument(e instanceof W1,"Invalid private key"),An.checkArgument(typeof t=="string","Challenge must be a string");var r=Ct.fromPrivateKey(e),i=new Date().toISOString(),n=t+":"+i+":"+r,o=Ct.signMessage(n,e);return{type:"EcdsaSecp256k1Signature2019",created:i,verificationMethod:r+"#keys-1",proofPurpose:"authentication",challenge:t,jws:o}};Ct.verifyProofOfOwnership=function(e,t){try{An.checkArgument(e&&typeof e=="object","Invalid proof object"),An.checkArgument(typeof t=="string","DID must be a string");var r=e.challenge+":"+e.created+":"+t;return Ct.verifyOwnership(t,e.jws,r)}catch{return!1}};Ct.createDIDURL=function(e,t){return An.checkArgument(typeof e=="string","DID must be a string"),An.checkArgument(typeof t=="string","Fragment must be a string"),e+"#"+t};Ct.generateTestDID=function(e){e=e||{};var t=new W1,r=Ct.fromPrivateKey(t,e),i=Ct.createDocument(r,e);return{did:r,privateKey:t.toWIF(),publicKey:t.toPublicKey().toString("hex"),document:i}};Mq.exports=Ct});var R5=k((Dme,Dq)=>{"use strict";v();var Wl=Te(),Cse=k5(),Nq=Wl.PrivateKey,Zs=Wl.crypto.Hash,Cq=Wl.crypto.ECDSA,Nme=Wl.crypto.Signature,Ws=Wl.util.preconditions,Cme=xt();function dr(e,t){return this instanceof dr?(typeof e=="string"&&(e=Nq.fromWIF(e)),Ws.checkArgument(e instanceof Nq,"Invalid private key"),this.privateKey=e,this.publicKey=e.toPublicKey(),this.options=t||{},this.did=Cse.fromPrivateKey(e,this.options),this):new dr(e,t)}dr._sortValue=function(e){return Array.isArray(e)?e.map(function(t){return dr._sortValue(t)}):e!==null&&typeof e=="object"?Object.keys(e).sort().reduce(function(t,r){return t[r]=dr._sortValue(e[r]),t},{}):e};dr._canonicalizeJSON=function(e){return JSON.stringify(dr._sortValue(e))};dr._hashCredential=function(e){var t=dr._canonicalizeJSON(e);return Zs.sha256(h.Buffer.from(t,"utf8"))};dr.prototype.createCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid credential subject");var r=new Date().toISOString(),i=t.id||"urn:uuid:"+this._generateUUID(),n={"@context":["https://www.w3.org/2018/credentials/v1"],id:i,type:["VerifiableCredential"],issuer:this.did,issuanceDate:r,credentialSubject:e};return t.type&&(Array.isArray(t.type)?n.type=n.type.concat(t.type):n.type.push(t.type)),t.context&&(Array.isArray(t.context)?n["@context"]=n["@context"].concat(t.context):n["@context"].push(t.context)),t.expirationDate&&(n.expirationDate=t.expirationDate),t.termsOfUse&&(n.termsOfUse=t.termsOfUse),t.evidence&&(n.evidence=t.evidence),t.refreshService&&(n.refreshService=t.refreshService),n};dr.prototype.signCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid credential");var r=JSON.parse(JSON.stringify(e));delete r.proof;var i=dr._hashCredential(r),n=new Cq;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:t.proofPurpose||"assertionMethod",jws:a};t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain);var u=JSON.parse(JSON.stringify(r));return u.proof=s,u.rootHash=i.toString("hex"),u};dr.prototype._createJWSSignature=function(e,t){var r={alg:"ES256K",typ:"JWT"},i=h.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o};dr.prototype.createEmailCredential=function(e,t){t=t||{},Ws.checkArgument(typeof e=="string"&&e.includes("@"),"Invalid email address");var r={id:t.subjectId||"did:smartledger:"+Zs.sha256(h.Buffer.from(e)).toString("hex"),email:e,verified:!0,verificationMethod:"email_verification",verificationTimestamp:new Date().toISOString()},i={type:"EmailVerifiedCredential",context:"https://smartledger.technology/contexts/email/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype.createAgeCredential=function(e,t,r){r=r||{},Ws.checkArgument(typeof e=="number"&&e>0,"Invalid age");var i={id:r.subjectId||"urn:uuid:"+this._generateUUID(),ageOver:e,verified:!0,verificationMethod:"age_verification"};t&&(i.birthDateHash=Zs.sha256(h.Buffer.from(t.toISOString())).toString("hex"));var n={type:"AgeVerifiedCredential",context:"https://smartledger.technology/contexts/age/v1",...r},o=this.createCredential(i,n);return this.signCredential(o,r)};dr.prototype.createKYCCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid KYC data");var r={id:t.subjectId||"urn:uuid:"+this._generateUUID(),kycLevel:e.level||"basic",verified:!0,verificationMethod:"kyc_verification",verificationTimestamp:new Date().toISOString(),verifyingAuthority:e.authority||this.did};e.firstName&&(r.firstNameHash=Zs.sha256(h.Buffer.from(e.firstName)).toString("hex")),e.lastName&&(r.lastNameHash=Zs.sha256(h.Buffer.from(e.lastName)).toString("hex")),e.ssn&&(r.ssnHash=Zs.sha256(h.Buffer.from(e.ssn)).toString("hex"));var i={type:"KYCVerifiedCredential",context:"https://smartledger.technology/contexts/kyc/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype.createOrganizationCredential=function(e,t){t=t||{},Ws.checkArgument(e&&typeof e=="object","Invalid organization data");var r={id:t.subjectId||"did:smartledger:org:"+Zs.sha256(h.Buffer.from(e.name||"")).toString("hex"),name:e.name,type:e.type||"Organization",verified:!0,verificationMethod:"organization_verification",verificationTimestamp:new Date().toISOString()};e.taxId&&(r.taxIdHash=Zs.sha256(h.Buffer.from(e.taxId)).toString("hex")),e.incorporationState&&(r.incorporationState=e.incorporationState),e.industry&&(r.industry=e.industry);var i={type:"OrganizationCredential",context:"https://smartledger.technology/contexts/organization/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};dr.prototype._generateUUID=function(){var e=Wl.crypto.Random.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")};dr.prototype.createPresentation=function(e,t){t=t||{},Ws.checkArgument(Array.isArray(e),"Credentials must be an array");var r={"@context":["https://www.w3.org/2018/credentials/v1"],type:["VerifiablePresentation"],id:t.id||"urn:uuid:"+this._generateUUID(),holder:this.did,verifiableCredential:e};t.context&&(Array.isArray(t.context)?r["@context"]=r["@context"].concat(t.context):r["@context"].push(t.context));var i=dr._hashCredential(r),n=new Cq;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:"authentication",jws:a};return t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain),r.proof=s,r};dr.prototype.getIssuerInfo=function(){return{did:this.did,publicKey:this.publicKey.toString("hex"),verificationMethod:this.did+"#keys-1"}};Dq.exports=dr});var Fq=k((Fme,Uq)=>{"use strict";v();var Y1=Te(),B5=k5(),$7=R5(),qme=Y1.PublicKey,Ume=Y1.crypto.Hash,Lq=Y1.crypto.ECDSA,Dse=Y1.crypto.Signature,qq=Y1.util.preconditions;function Mt(e){return this instanceof Mt?(this.options=e||{},this.trustedIssuers=this.options.trustedIssuers||[],this):new Mt(e)}Mt.verifyCredential=async function(e,t){t=t||{};try{qq.checkArgument(e&&typeof e=="object","Invalid credential");var r={valid:!1,errors:[],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}},i=Mt._validateStructure(e);r.checks.structure=i.valid,i.valid||(r.errors=r.errors.concat(i.errors));var n=await Mt._verifySignature(e);r.checks.signature=n.valid,n.valid?(r.issuerDID=n.issuerDID,r.verificationMethod=n.verificationMethod):r.errors=r.errors.concat(n.errors);var o=await Mt._validateIssuer(e,t);r.checks.issuer=o.valid,o.valid||(r.errors=r.errors.concat(o.errors)),o.warnings&&(r.warnings=r.warnings.concat(o.warnings));var a=Mt._validateTemporal(e);if(r.checks.temporal=a.valid,a.valid||(r.errors=r.errors.concat(a.errors)),a.warnings&&(r.warnings=r.warnings.concat(a.warnings)),t.schema){var s=Mt._validateSchema(e,t.schema);r.checks.schema=s.valid,s.valid||(r.errors=r.errors.concat(s.errors))}else r.checks.schema=!0;return r.valid=Object.values(r.checks).every(u=>u===!0),r}catch(u){return{valid:!1,errors:["Verification failed: "+u.message],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}}}};Mt.verifyPresentation=async function(e,t){t=t||{};try{qq.checkArgument(e&&typeof e=="object","Invalid presentation");var r={valid:!1,errors:[],warnings:[],credentialResults:[],presentationValid:!1};if(!e.type||!e.type.includes("VerifiablePresentation"))return r.errors.push("Invalid presentation type"),r;if(!e.holder)return r.errors.push("Missing presentation holder"),r;var i=await Mt._verifyPresentationSignature(e);if(r.presentationValid=i.valid,i.valid||(r.errors=r.errors.concat(i.errors)),e.verifiableCredential&&Array.isArray(e.verifiableCredential))for(var n=0;n<e.verifiableCredential.length;n++){var o=e.verifiableCredential[n],a=await Mt.verifyCredential(o,t);r.credentialResults.push({index:n,result:a}),a.valid||r.errors.push("Credential "+n+" is invalid")}var s=r.credentialResults.every(u=>u.result.valid);return r.valid=r.presentationValid&&s,r}catch(u){return{valid:!1,errors:["Presentation verification failed: "+u.message],warnings:[],credentialResults:[],presentationValid:!1}}};Mt._validateStructure=function(e){var t=[];return e["@context"]?Array.isArray(e["@context"])?e["@context"].includes("https://www.w3.org/2018/credentials/v1")||t.push("Missing required W3C credentials context"):t.push("@context must be an array"):t.push("Missing @context"),e.type?Array.isArray(e.type)?e.type.includes("VerifiableCredential")||t.push("Must include VerifiableCredential type"):t.push("type must be an array"):t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof"),{valid:t.length===0,errors:t}};Mt._normalizeDID=function(e){var t=e&&typeof e=="object"?e.id:e;return typeof t!="string"||t.length===0?null:t.split("#")[0]};Mt._verifySignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing proof"]};if(t.type!=="EcdsaSecp256k1Signature2019")return{valid:!1,errors:["Unsupported proof type: "+t.type]};if(!t.verificationMethod)return{valid:!1,errors:["Missing verification method"]};if(!t.jws)return{valid:!1,errors:["Missing JWS signature"]};var r=t.verificationMethod,i=r.split("#")[0],n=Mt._normalizeDID(e.issuer);if(!n)return{valid:!1,errors:["Missing or invalid credential issuer"]};if(n!==i)return{valid:!1,errors:["Verification method DID ("+i+") does not match credential issuer ("+n+")"]};var o=B5.getPublicKey(i),a=JSON.parse(JSON.stringify(e));delete a.proof,delete a.rootHash;var s=$7._hashCredential(a),u=Mt._parseJWSSignature(t.jws),c=new Lq;c.hashbuf=s,c.pubkey=o,c.sig=u;var l=c.verify();return l?{valid:!0,issuerDID:i,verificationMethod:r}:{valid:!1,errors:["Signature verification failed"]}}catch(m){return{valid:!1,errors:["Signature verification error: "+m.message]}}};Mt._parseJWSSignature=function(e){var t=e.split(".");if(t.length!==3)throw new Error("Invalid JWS format");var r=t[2],i=h.Buffer.from(r,"base64url");return Dse.fromDER(i)};Mt._verifyPresentationSignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing presentation proof"]};var r=e.holder,i=B5.getPublicKey(r),n=JSON.parse(JSON.stringify(e));delete n.proof;var o=$7._hashCredential(n),a=Mt._parseJWSSignature(t.jws),s=new Lq;s.hashbuf=o,s.pubkey=i,s.sig=a;var u=s.verify();return{valid:u,errors:u?[]:["Presentation signature verification failed"]}}catch(c){return{valid:!1,errors:["Presentation signature error: "+c.message]}}};Mt._validateIssuer=async function(e,t){var r=[],i=[];try{var n=e.issuer;if(!B5.isValidDID(n))return r.push("Invalid issuer DID format"),{valid:!1,errors:r};var o=await B5.resolve(n);if(!o.didDocument)return r.push("Unable to resolve issuer DID"),{valid:!1,errors:r};if(t.trustedIssuers&&Array.isArray(t.trustedIssuers)){var a=Mt._normalizeDID(n),s=t.trustedIssuers.map(function(u){return Mt._normalizeDID(u)}).filter(Boolean);if(!a||s.indexOf(a)===-1)return r.push("Issuer not in trusted list"),{valid:!1,errors:r,warnings:i}}return{valid:r.length===0,errors:r,warnings:i}}catch(u){return{valid:!1,errors:["Issuer validation error: "+u.message],warnings:i}}};Mt._validateTemporal=function(e){var t=[],r=[],i=new Date;if(e.issuanceDate){var n=new Date(e.issuanceDate);isNaN(n.getTime())?t.push("Invalid issuanceDate format"):n>i&&t.push("Credential issued in the future")}if(e.expirationDate){var o=new Date(e.expirationDate);isNaN(o.getTime())?t.push("Invalid expirationDate format"):o<=i?t.push("Credential has expired"):o<=new Date(i.getTime()+1440*60*1e3)&&r.push("Credential expires within 24 hours")}return{valid:t.length===0,errors:t,warnings:r}};Mt._validateSchema=function(e,t){var r=[];if(t.requiredFields&&t.requiredFields.forEach(function(n){Mt._getNestedProperty(e,n)||r.push("Missing required field: "+n)}),t.requiredTypes){var i=t.requiredTypes.some(function(n){return e.type&&e.type.includes(n)});i||r.push("Missing required credential type")}return{valid:r.length===0,errors:r}};Mt._getNestedProperty=function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)};Mt.verifyCredentialHash=function(e){try{if(!e.rootHash)return!1;var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.rootHash;var r=$7._hashCredential(t),i=h.Buffer.from(e.rootHash,"hex");return h.Buffer.compare(r,i)===0}catch{return!1}};Mt.extractClaims=function(e){try{var t={issuer:e.issuer,subject:e.credentialSubject.id||"unknown",types:e.type||[],issuanceDate:e.issuanceDate,expirationDate:e.expirationDate,claims:{}};return Object.keys(e.credentialSubject).forEach(function(r){r!=="id"&&(t.claims[r]=e.credentialSubject[r])}),t}catch{return null}};Mt.createReport=function(e){var t=[];return t.push("=== Credential Verification Report ==="),t.push("Overall Status: "+(e.valid?"VALID":"INVALID")),t.push(""),t.push("Verification Checks:"),Object.keys(e.checks).forEach(function(r){var i=e.checks[r]?"\u2713":"\u2717";t.push(" "+i+" "+r.charAt(0).toUpperCase()+r.slice(1))}),t.push(""),e.errors.length>0&&(t.push("Errors:"),e.errors.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.warnings.length>0&&(t.push("Warnings:"),e.warnings.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.issuerDID&&t.push("Issuer: "+e.issuerDID),e.verificationMethod&&t.push("Verification Method: "+e.verificationMethod),t.join(`
102
102
  `)};Uq.exports=Mt});var jq=k((zme,Hq)=>{"use strict";v();var Gf=Te(),Lse=R5(),co=Gf.crypto.Hash,jme=Gf.crypto.BN,ai=Gf.util.preconditions;function ir(e){return this instanceof ir?(this.options=e||{},this):new ir(e)}ir.createMerkleTree=function(e,t){t=t||Gf.crypto.Random.getRandomBuffer(32).toString("hex"),ai.checkArgument(e&&typeof e=="object","Invalid credential");var r=ir._extractFields(e),i=r.map(function(o){var a=o.path+":"+JSON.stringify(o.value)+":"+t;return{path:o.path,value:o.value,hash:co.sha256(h.Buffer.from(a,"utf8")).toString("hex"),salt:t}}),n=ir._buildMerkleTree(i.map(o=>o.hash));return{salt:t,leaves:i,tree:n,root:n[n.length-1][0]}};ir.generateSelectiveProof=function(e,t,r){ai.checkArgument(e&&typeof e=="object","Invalid credential"),typeof t=="string"&&(t=[t]),ai.checkArgument(Array.isArray(t),"Disclose paths must be array");var i=ir.createMerkleTree(e,r),n=[],o=[];return t.forEach(function(a){var s=i.leaves.find(l=>l.path===a);if(s){n.push(s);var u=i.leaves.findIndex(l=>l.path===a),c=ir._generateMerkleProof(i.tree,u);o.push({path:a,leafIndex:u,proof:c})}}),{type:"SelectiveDisclosureProof",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,credentialRoot:i.root,credentialHash:e.rootHash||Lse._hashCredential(e).toString("hex"),disclosedFields:n.map(function(a){return{path:a.path,value:a.value,hash:a.hash}}),merkleProofs:o,salt:r}};ir.verifySelectiveProof=function(e,t){try{ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="string","Expected root must be string");for(var r={valid:!1,errors:[],verifiedFields:[]},i=0;i<e.disclosedFields.length;i++){var n=e.disclosedFields[i],o=e.merkleProofs.find(c=>c.path===n.path);if(!o){r.errors.push("Missing Merkle proof for field: "+n.path);continue}var a=n.path+":"+JSON.stringify(n.value)+":"+e.salt,s=co.sha256(h.Buffer.from(a,"utf8")).toString("hex");if(s!==n.hash){r.errors.push("Field hash mismatch for: "+n.path);continue}var u=ir._verifyMerkleProof(n.hash,o.proof,t);if(!u){r.errors.push("Invalid Merkle proof for: "+n.path);continue}r.verifiedFields.push({path:n.path,value:n.value,verified:!0})}return r.valid=r.errors.length===0&&r.verifiedFields.length>0,r}catch(c){return{valid:!1,errors:["Proof verification failed: "+c.message],verifiedFields:[]}}};ir.generateAgeProof=function(e,t,r){ai.checkArgument(e instanceof Date,"Birth date must be Date object"),ai.checkArgument(typeof t=="number","Minimum age must be number"),r=r||Gf.crypto.Random.getRandomBuffer(32).toString("hex");var i=new Date,n=Math.floor((i-e)/(365.25*24*60*60*1e3));if(n<t)throw new Error("Age requirement not met");var o=e.toISOString().split("T")[0],a=co.sha256(h.Buffer.from(o+":"+r,"utf8")).toString("hex"),s={minimumAge:t,ageAttestation:n>=t,timestamp:i.toISOString(),salt:r},u=co.sha256(h.Buffer.from(JSON.stringify(s),"utf8")).toString("hex");return{type:"AgeProof",created:new Date().toISOString(),proofPurpose:"ageVerification",minimumAge:t,meetsRequirement:!0,birthDateCommitment:a,ageProofHash:u,challengeResponse:ir._generateAgeChallenge(e,t,r)}};ir.verifyAgeProof=function(e,t){try{return ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="number","Required age must be number"),e.type!=="AgeProof"||e.minimumAge!==t||!e.meetsRequirement?!1:e.challengeResponse&&e.challengeResponse.length>0}catch{return!1}};ir.generateRangeProof=function(e,t,r,i){ai.checkArgument(typeof e=="number","Value must be number"),ai.checkArgument(typeof t=="number","Min must be number"),ai.checkArgument(typeof r=="number","Max must be number"),ai.checkArgument(e>=t&&e<=r,"Value not in range"),i=i||Gf.crypto.Random.getRandomBuffer(32).toString("hex");var n=co.sha256(h.Buffer.from(e.toString()+":"+i,"utf8")).toString("hex"),o={min:t,max:r,inRange:!0,timestamp:new Date().toISOString(),salt:i},a=co.sha256(h.Buffer.from(JSON.stringify(o),"utf8")).toString("hex");return{type:"RangeProof",created:new Date().toISOString(),proofPurpose:"rangeVerification",range:{min:t,max:r},valueCommitment:n,proofHash:a,inRange:!0}};ir.verifyRangeProof=function(e,t,r){try{return ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="RangeProof"||e.range.min!==t||e.range.max!==r?!1:e.inRange===!0}catch{return!1}};ir._extractFields=function(e,t){t=t||"";var r=[];return Object.keys(e).forEach(function(i){var n=t?t+"."+i:i,o=e[i];o&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?r=r.concat(ir._extractFields(o,n)):r.push({path:n,value:o})}),r};ir._buildMerkleTree=function(e){if(e.length===0)throw new Error("Cannot build tree from empty leaves");for(var t=[e];t[t.length-1].length>1;){for(var r=t[t.length-1],i=[],n=0;n<r.length;n+=2){var o=r[n],a=n+1<r.length?r[n+1]:o,s=o+a,u=co.sha256(h.Buffer.from(s,"hex")).toString("hex");i.push(u)}t.push(i)}return t};ir._generateMerkleProof=function(e,t){for(var r=[],i=t,n=0;n<e.length-1;n++){var o=e[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r};ir._verifyMerkleProof=function(e,t,r){for(var i=e,n=0;n<t.length;n++){var o=t[n],a=o.isLeft?o.hash+i:i+o.hash;i=co.sha256(h.Buffer.from(a,"hex")).toString("hex")}return i===r};ir._generateAgeChallenge=function(e,t,r){var i=co.sha256(h.Buffer.from(e.toISOString()+t+r,"utf8"));return i.toString("hex")};ir.generateMembershipProof=function(e,t,r){ai.checkArgument(Array.isArray(e),"Set must be array"),ai.checkArgument(e.includes(t),"Value not in set"),r=r||Gf.crypto.Random.getRandomBuffer(32).toString("hex");var i=e.map(function(o){return co.sha256(h.Buffer.from(JSON.stringify(o)+":"+r,"utf8")).toString("hex")}),n=co.sha256(h.Buffer.from(JSON.stringify(t)+":"+r,"utf8")).toString("hex");return{type:"MembershipProof",created:new Date().toISOString(),proofPurpose:"membershipVerification",setCommitments:i,valueCommitment:n,isMember:!0}};ir.verifyMembershipProof=function(e){try{return ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="MembershipProof"||!Array.isArray(e.setCommitments)?!1:e.setCommitments.includes(e.valueCommitment)&&e.isMember}catch{return!1}};Hq.exports=ir});var Vq=k((Gme,Kq)=>{"use strict";v();var Zf=Te(),X7=Zf.Transaction,qse=Zf.Script,J7=Zf.PrivateKey,Vme=Zf.Address,$1=Zf.crypto.Hash,zq=Zf.SPV,Ys=Zf.util.preconditions;function kr(e,t){return this instanceof kr?(typeof e=="string"&&(e=J7.fromWIF(e)),e!==null?(Ys.checkArgument(e instanceof J7,"Invalid private key"),this.privateKey=e,this.address=e.toAddress()):(this.privateKey=null,this.address=null),this.options=t||{},this.network=this.options.network||"mainnet",this.PROTOCOL_ID="SMARTLEDGER.ATTEST",this.VERSION=1,this):new kr(e,t)}kr.prototype.anchorCredential=async function(e,t,r){t=t||{},typeof e=="string"&&(e=h.Buffer.from(e,"hex")),Ys.checkArgument(h.Buffer.isBuffer(e),"Invalid credential hash"),Ys.checkArgument(e.length===32,"Hash must be 32 bytes");var i=this._createAnchorPayload("CREDENTIAL",e,t),n=await this._createAnchorTransaction(i,r);return{txid:n.hash,transaction:n,anchorHash:e.toString("hex"),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"CREDENTIAL"}}};kr.prototype.anchorBatch=async function(e,t,r){t=t||{},Ys.checkArgument(Array.isArray(e),"Credential hashes must be array"),Ys.checkArgument(e.length>0,"Must provide at least one hash");var i=this._createMerkleRoot(e),n=this._createAnchorPayload("BATCH",i,{...t,batchSize:e.length,merkleRoot:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,merkleRoot:i.toString("hex"),batchSize:e.length,credentialHashes:e.map(a=>h.Buffer.isBuffer(a)?a.toString("hex"):a),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"BATCH"}}};kr.prototype.registerDID=async function(e,t,r){Ys.checkArgument(typeof e=="string","DID must be string"),Ys.checkArgument(t&&typeof t=="object","Invalid DID document");var i=$1.sha256(h.Buffer.from(JSON.stringify(t),"utf8")),n=this._createAnchorPayload("DID_REG",i,{did:e,operation:"create",documentHash:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,did:e,documentHash:i.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"DID_REG"}}};kr.prototype.revokeCredential=async function(e,t,r){Ys.checkArgument(typeof e=="string","Credential ID must be string"),t=t||"unspecified";var i={credentialId:e,reason:t,timestamp:new Date().toISOString(),issuer:this.address.toString()},n=$1.sha256(h.Buffer.from(JSON.stringify(i),"utf8")),o=this._createAnchorPayload("REVOKE",n,{credentialId:e,reason:t}),a=await this._createAnchorTransaction(o,r);return{txid:a.hash,transaction:a,credentialId:e,reason:t,revocationHash:n.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"REVOKE"}}};function Use(e){var t=["bn","privateKey","privkey","wif","privateJwk","d","seed","xpriv","xprv"];function r(i,n,o){if(!(!i||typeof i!="object"||o>4)){if(typeof i.toWIF=="function"&&i.bn)throw new Error("Refusing to anchor: "+(n||"metadata")+" is a PrivateKey. Anchor metadata is published in the OP_RETURN and must never contain key material.");Object.keys(i).forEach(function(a){if(t.indexOf(a)!==-1&&i[a]!=null&&typeof i[a]!="object")throw new Error("Refusing to anchor: "+(n?n+".":"")+a+" looks like key material, and anchor metadata is published in the OP_RETURN.");r(i[a],n?n+"."+a:a,o+1)})}}r(e,"",0)}kr.prototype._createAnchorPayload=function(e,t,r){var i=Math.floor(Date.now()/1e3);Use(r);var n=h.Buffer.concat([h.Buffer.from(this.PROTOCOL_ID,"utf8"),h.Buffer.from([this.VERSION]),h.Buffer.from(e.padEnd(10,"\0"),"utf8"),h.Buffer.from([i>>24,i>>16,i>>8,i]),t,h.Buffer.from(JSON.stringify(r),"utf8")]);return n};kr.prototype._createAnchorTransaction=async function(e,t){if(!t||t.length===0)throw new Error("UTXOs required for anchor transaction");var r=200+e.length,i=this.options.feeRate||1,n=r*i,o=t.reduce((c,l)=>c+l.satoshis,0);if(o<n)throw new Error("Insufficient funds for anchor transaction");var a=new X7;t.forEach(c=>{a.from(c)});var s=qse.buildDataOut(e);a.addOutput(new X7.Output({script:s,satoshis:0}));var u=o-n;return u>546&&a.to(this.address,u),a.sign(this.privateKey),a};kr.prototype._createMerkleRoot=function(e){if(e.length===0)throw new Error("Cannot create Merkle root from empty array");for(var t=e.map(u=>h.Buffer.isBuffer(u)?u:h.Buffer.from(u,"hex"));t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=i+1<t.length?t[i+1]:n,a=h.Buffer.concat([n,o]),s=$1.sha256(a);r.push(s)}t=r}return t[0]};kr.parseAnchorData=function(e){if(!h.Buffer.isBuffer(e))throw new Error("Data must be Buffer");if(e.length<50)throw new Error("Data too short for SmartLedger anchor");var t=0,r=18,i=e.slice(t,t+r).toString("utf8");if(t+=r,i!=="SMARTLEDGER.ATTEST")throw new Error("Invalid protocol identifier");var n=e[t];t+=1;var o=e.slice(t,t+10).toString("utf8").replace(/\0/g,"");t+=10;var a=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];t+=4;var s=e.slice(t,t+32);t+=32;var u=e.slice(t),c={};try{c=JSON.parse(u.toString("utf8"))}catch{}return{protocol:i,version:n,type:o,timestamp:new Date(a*1e3),hash:s.toString("hex"),metadata:c}};kr.verifyAnchor=async function(e,t,r){if(r=r||{},!e||!t)throw new Error("verifyAnchor requires both txid and expectedHash");if(r.spvProof&&(r.header||r.headerChain)&&r.rawTx)return kr._verifyAnchorSPV(e,t,r);if(typeof r.chainProvider!="function")throw new Error("verifyAnchor needs either a trustless SPV proof \u2014 { spvProof: { index, nodes }, header, rawTx } \u2014 or a trusted options.chainProvider(txid) returning { confirmations, blockHeight, opReturns }. Refusing to fabricate a result.");var i=r.minConfirmations!=null?r.minConfirmations:1,n=await r.chainProvider(e),o=n&&n.confirmations||0,a=n&&n.opReturns||[],s=String(t).toLowerCase(),u=a.some(function(l){return String(l).toLowerCase().indexOf(s)!==-1}),c=o>=i&&u;return{verified:c,txid:e,hash:t,committed:u,confirmations:o,blockHeight:n&&n.blockHeight||null,timestamp:new Date().toISOString(),proof:{type:"blockchain_anchor",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};kr._verifyAnchorSPV=function(e,t,r){var i=r.spvProof||{},n=null,o=r.header;r.headerChain&&(n=zq.verifyHeaderChain(r.headerChain,{requirePow:r.requirePow!==!1,trustedHash:r.trustedHash}),o=r.headerChain[0]);var a=zq.verifyTxInclusion({txid:e,index:i.index,nodes:i.nodes,header:o,requirePow:r.requirePow!==!1}),s=h.Buffer.isBuffer(r.rawTx)?r.rawTx:h.Buffer.from(r.rawTx,"hex"),u=h.Buffer.from($1.sha256sha256(s)).reverse().toString("hex"),c=u.toLowerCase()===String(e).toLowerCase(),l=c&&kr._rawTxCommitsTo(s,t),m=n?n.count:r.header?1:0,w=r.minConfirmations!=null?r.minConfirmations:1,E=n?n.valid:!0,P=m>=w;return{verified:a.valid&&c&&l&&E&&P,chainVerified:a.valid,committed:l,txidBound:c,powValid:a.powValid,confirmations:m,headerChainValid:n?n.valid:null,headerChainReason:n&&n.reason||null,tipHash:n?n.tipHash:null,txid:e,hash:t,blockHash:a.blockHash,merkleRoot:a.merkleRoot,timestamp:new Date().toISOString(),proof:{type:n?"spv_merkle_inclusion_with_confirmations":"spv_merkle_inclusion",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};kr._rawTxCommitsTo=function(e,t){var r=String(t).toLowerCase(),i;try{i=new X7(e)}catch{return!1}return i.outputs.some(function(n){var o=n.script;if(!o||!o.chunks||!o.chunks.length)return!1;var a=o.chunks[0].opcodenum===106||o.chunks[0].opcodenum===0&&o.chunks[1]&&o.chunks[1].opcodenum===106;return a?o.chunks.some(function(s){return s.buf&&s.buf.toString("hex").toLowerCase().indexOf(r)!==-1}):!1})};kr.getCostEstimate=function(e,t){t=t||{};var r=t.feeRate||1,i=200,n=32,o=e*(i+n)*r,a=(i+e*n)*r;return{individual:{totalCost:o,costPerHash:i*r,transactions:e},batch:{totalCost:a,costPerHash:Math.ceil(a/e),transactions:1},savings:{absolute:o-a,percentage:Math.round((o-a)/o*100)}}};kr.createUTXO=function(e,t,r,i){return{txid:e,outputIndex:t,satoshis:r,script:i}};kr.generateTestData=function(){var e=new J7,t=new kr(e),r=$1.sha256(h.Buffer.from("test credential data")),i={issuer:"did:smartledger:test",type:"EmailVerifiedCredential",environment:"test"};return{privateKey:e.toWIF(),address:e.toAddress().toString(),credentialHash:r.toString("hex"),metadata:i,anchor:t}};Kq.exports=kr});var Zq=k((Wme,Gq)=>{"use strict";v();var Q7=Bt(),X1={EmailVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/email/v1"],type:["VerifiableCredential","EmailVerifiedCredential"],requiredFields:["credentialSubject.email","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["email","verified"],properties:{email:{type:"string",format:"email"},verified:{type:"boolean"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},AgeVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/age/v1"],type:["VerifiableCredential","AgeVerifiedCredential"],requiredFields:["credentialSubject.ageOver","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["ageOver","verified"],properties:{ageOver:{type:"number",minimum:0,maximum:150},verified:{type:"boolean"},birthDateHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verificationMethod:{type:"string"}}}}},KYCVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/kyc/v1"],type:["VerifiableCredential","KYCVerifiedCredential"],requiredFields:["credentialSubject.kycLevel","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["kycLevel","verified","verifyingAuthority"],properties:{kycLevel:{type:"string",enum:["basic","enhanced","premium","institutional"]},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},firstNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},lastNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"}}}}},OrganizationCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/organization/v1"],type:["VerifiableCredential","OrganizationCredential"],requiredFields:["credentialSubject.name","credentialSubject.type","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["name","type","verified"],properties:{name:{type:"string"},type:{type:"string",enum:["Corporation","LLC","Partnership","NGO","Government","Other"]},verified:{type:"boolean"},taxIdHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},incorporationState:{type:"string"},industry:{type:"string"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},SSNVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ssn/v1"],type:["VerifiableCredential","SSNVerifiedCredential"],requiredFields:["credentialSubject.ssnHash","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["ssnHash","verified","verifyingAuthority"],properties:{ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},issuingState:{type:"string"}}}}},EducationalCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/education/v1"],type:["VerifiableCredential","EducationalCredential"],requiredFields:["credentialSubject.degree","credentialSubject.institution","credentialSubject.graduationDate"],properties:{credentialSubject:{type:"object",required:["degree","institution","graduationDate"],properties:{degree:{type:"string"},institution:{type:"string"},graduationDate:{type:"string",format:"date"},gpa:{type:"number",minimum:0,maximum:4},major:{type:"string"},honors:{type:"array",items:{type:"string"}}}}}},ProfessionalLicenseCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/license/v1"],type:["VerifiableCredential","ProfessionalLicenseCredential"],requiredFields:["credentialSubject.licenseType","credentialSubject.licenseNumber","credentialSubject.issuingAuthority","credentialSubject.isValid"],properties:{credentialSubject:{type:"object",required:["licenseType","licenseNumber","issuingAuthority","isValid"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},issuingState:{type:"string"},isValid:{type:"boolean"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"}}}}}},Fse={getSchema:function(e){return X1[e]||null},getAllSchemas:function(){return X1},validate:function(e,t){try{Q7.checkArgument(e&&typeof e=="object","Invalid credential");var r;if(typeof t=="string"){if(r=X1[t],!r)return{valid:!1,errors:["Unknown schema type: "+t]}}else if(typeof t=="object")r=t;else return{valid:!1,errors:["Invalid schema parameter"]};var i=[],n=[];return this._validateCredentialStructure(e,i),this._validateCredentialTypes(e,r,i),this._validateRequiredFields(e,r,i),this._validateFieldProperties(e,r,i,n),{valid:i.length===0,errors:i,warnings:n}}catch(o){return{valid:!1,errors:["Schema validation error: "+o.message]}}},_validateCredentialStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.type||t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject")},_validateCredentialTypes:function(e,t,r){if(!Array.isArray(e.type)){r.push("Credential type must be array");return}if(t.type&&Array.isArray(t.type))for(var i=0;i<t.type.length;i++)e.type.includes(t.type[i])||r.push("Missing required type: "+t.type[i])},_validateRequiredFields:function(e,t,r){if(t.requiredFields&&Array.isArray(t.requiredFields))for(var i=0;i<t.requiredFields.length;i++){var n=t.requiredFields[i],o=this._getNestedProperty(e,n);o==null&&r.push("Missing required field: "+n)}},_validateFieldProperties:function(e,t,r,i){t.properties&&t.properties.credentialSubject&&this._validateObjectProperties(e.credentialSubject,t.properties.credentialSubject,"credentialSubject",r,i)},_validateObjectProperties:function(e,t,r,i,n){!e||typeof e!="object"||t.properties&&Object.keys(t.properties).forEach(function(o){var a=e[o],s=t.properties[o],u=r+"."+o;a!=null&&this._validateProperty(a,s,u,i,n)}.bind(this))},_validateProperty:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.format==="email"&&!this._isValidEmail(e)&&i.push("Invalid email format for "+r),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r),t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e)),t.type==="number"&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateProperty(e[a],t.items,r+"["+a+"]",i,n)},_getNestedProperty:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_isValidEmail:function(e){var t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return t.test(e)},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())},addSchema:function(e,t){Q7.checkArgument(typeof e=="string","Schema name must be string"),Q7.checkArgument(t&&typeof t=="object","Invalid schema definition"),X1[e]=t},createTemplate:function(e){var t=X1[e];if(!t)throw new Error("Unknown credential type: "+e);var r={"@context":t["@context"]||["https://www.w3.org/2018/credentials/v1"],type:t.type||["VerifiableCredential"],issuer:"did:smartledger:ISSUER_DID_HERE",issuanceDate:new Date().toISOString(),credentialSubject:this._createSubjectTemplate(t.properties?t.properties.credentialSubject:{})};return r},_createSubjectTemplate:function(e){var t={id:"SUBJECT_ID_HERE"};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t},_getDefaultValue:function(e){switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="email"?"example@example.com":e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":return e.minimum||0;case"boolean":return!0;case"array":return[];case"object":return{};default:return null}}};Gq.exports=Fse});var W7=k(($me,Wq)=>{"use strict";v();var Hse=k5(),Yl=R5(),jse=Fq(),zse=jq(),J1=Vq(),Kse=Zq();function pt(e){if(!(this instanceof pt))return new pt(e);e=e||{},this.didResolver=Hse,this.attestationVerifier=jse,this.zkProver=zse,this.schemaValidator=Kse,this._attestationSignerOptions=e.attestationSigner||{},this._anchorOptions=e.anchor||{}}pt.prototype.createDID=function(e){return this.didResolver.fromPublicKey(e)};pt.prototype.resolveDID=function(e){return this.didResolver.resolve(e)};pt.prototype.verifyDIDOwnership=function(e,t){return this.didResolver.verifyOwnership(e,t)};pt.prototype.createEmailCredential=function(e,t,r,i){var n=new Yl(i,this._attestationSignerOptions);return n.createEmailCredential(r,{issuerDID:e,subjectId:t})};pt.prototype.createAgeCredential=function(e,t,r,i,n){var o=new Yl(n,this._attestationSignerOptions);return o.createAgeCredential(r,i,{issuerDID:e,subjectId:t})};pt.prototype.createKYCCredential=function(e,t,r,i,n){var o=new Yl(n,this._attestationSignerOptions),a=Object.assign({level:r},i);return o.createKYCCredential(a,{issuerDID:e,subjectId:t})};pt.prototype.createOrganizationCredential=function(e,t,r,i){var n=new Yl(i,this._attestationSignerOptions);return n.createOrganizationCredential(r,{issuerDID:e,subjectId:t})};pt.prototype.createPresentation=function(e,t,r,i){var n=new Yl(r,this._attestationSignerOptions);return n.createPresentation(e,t,r,i)};pt.prototype.signCredential=function(e,t){var r=new Yl(t,this._attestationSignerOptions);return r.signCredential(e,t)};pt.prototype.verifyCredential=function(e,t){return this.attestationVerifier.verifyCredential(e,t)};pt.prototype.verifyPresentation=function(e,t){return this.attestationVerifier.verifyPresentation(e,t)};pt.prototype.extractClaims=function(e){return this.attestationVerifier.extractClaims(e)};pt.prototype.generateSelectiveProof=function(e,t,r){return this.zkProver.generateSelectiveProof(e,t,r)};pt.prototype.verifySelectiveProof=function(e,t){return this.zkProver.verifySelectiveProof(e,t)};pt.prototype.generateAgeProof=function(e,t,r){var i=new Date("1995-06-15");return this.zkProver.generateAgeProof(i,t,r)};pt.prototype.verifyAgeProof=function(e,t,r){return this.zkProver.verifyAgeProof(e,t,r)};pt.prototype.generateRangeProof=function(e,t,r,i){return this.zkProver.generateRangeProof(e,t,r,i)};pt.prototype.verifyRangeProof=function(e,t,r){return this.zkProver.verifyRangeProof(e,t,r)};pt.prototype.generateMembershipProof=function(e,t,r){return this.zkProver.generateMembershipProof(e,t,r)};pt.prototype.verifyMembershipProof=function(e,t){return this.zkProver.verifyMembershipProof(e,t)};function M5(e){return Array.isArray(e)?{metadata:void 0,utxos:e}:(e=e||{},{metadata:e.metadata,utxos:e.utxos})}pt.prototype.anchorCredential=function(e,t,r){var i=new J1(t,this._anchorOptions),n=M5(r);return i.anchorCredential(e,n.metadata,n.utxos)};pt.prototype.anchorBatch=function(e,t,r){var i=new J1(t,this._anchorOptions),n=M5(r);return i.anchorBatch(e,n.metadata,n.utxos)};pt.prototype.registerDID=function(e,t,r,i){var n=new J1(r,this._anchorOptions);return n.registerDID(e,t,M5(i).utxos)};pt.prototype.revokeCredential=function(e,t,r,i){var n=new J1(r,this._anchorOptions);return n.revokeCredential(e,t,M5(i).utxos)};pt.prototype.queryAnchoredData=function(e){var t=new J1(null,this._anchorOptions);return t.queryAnchoredData(e)};pt.prototype.validateCredential=function(e,t){return this.schemaValidator.validate(e,t)};pt.prototype.getSchema=function(e){return this.schemaValidator.getSchema(e)};pt.prototype.getAllSchemas=function(){return this.schemaValidator.getAllSchemas()};pt.prototype.addSchema=function(e,t){return this.schemaValidator.addSchema(e,t)};pt.prototype.createTemplate=function(e){return this.schemaValidator.createTemplate(e)};pt.prototype.generateNonce=function(e){e=e||32;var t=_r();return t.randomBytes(e).toString("hex")};pt.prototype.hashData=function(e,t){var r=_r(),i=r.createHash("sha256");return i.update(e),t&&i.update(t),i.digest("hex")};pt.prototype.getVersion=function(){return"1.0.0"};pt.prototype.getInfo=function(){return{name:"SmartLedger BSV Global Digital Attestation Framework",version:this.getVersion(),description:"W3C-compliant verifiable credentials with DID resolution, zero-knowledge proofs, and blockchain anchoring",components:{didResolver:"DID Resolution and Management",attestationSigner:"Verifiable Credential Creation",attestationVerifier:"Credential and Presentation Verification",zkProver:"Zero-Knowledge Proof Generation and Verification",anchor:"Blockchain Anchoring and Timestamping",schemaValidator:"W3C VC Schema Validation"},standards:["W3C Verifiable Credentials Data Model v1.1","W3C Decentralized Identifiers (DIDs) v1.0","RFC 7515 JSON Web Signature (JWS)","BSV Blockchain Protocol"]}};Wq.exports=pt});var Vse=k((Jme,Yq)=>{v();Yq.exports=W7()});return Vse();})();
103
103
  if(typeof module!=="undefined"&&module.exports){module.exports=bsvGDAF}else if(typeof define==="function"&&define.amd){define([],function(){return bsvGDAF})}